How to Find Partial Text in Multiple Elements with Selenium?

I'm trying to find partial text inside web page's <p> elements, which contains specific string. While I know how to find the whole text, I don't know how to find only a partial text, if it matches.

For example, if a text between p tags contains "Lorem ipsum" and my string is "ipsum", the script should find it in the text.

Here's my code so far:

#elem = driver.find_element_by_tag_name('p').text
elem = driver.find_element(By.XPATH, "//p[contains(text(), ' "+string" ')]").get_attribute('text')

if title in elem:
    print(title)

What am I doing wrong?

2 Answers

You missed one concatenation +

try now.

string="ipsum"

elem = driver.find_element(By.XPATH, "//p[contains(text(), '" + string + "')]").text

The other way is to do it using python format function.

string="ipsum"

elem = driver.find_element(By.XPATH, f"//p[contains(text(), '{string}')]").text

or

string="ipsum"

elem = driver.find_element(By.XPATH, f"//p[contains(., '{string}')]").text

or

string="ipsum"

elem = driver.find_element(By.XPATH, "//p[contains(., '{}')]".format(string)).text
2

Given the sample HTML

<p>Lorem ipsum dolor sit amet</p>
<p>consectetur adipiscing elit</p>
<p>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p>Ut enim ad minim veniam</p>
<p>quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur</p>
<p>Excepteur sint occaecat cupidatat non proident</p>
<p>sunt in culpa qui officia deserunt mollit anim id est laborum</p>

You could use the code

search_string = "Lorem sint"
for s in search_string.split(" "):
    print(driver.find_element(By.XPATH, f"//p[contains(text(), '{s}')]").text)

and it prints

Lorem ipsum dolor sit amet
Excepteur sint occaecat cupidatat non proident

It just takes the search string, splits it by a space, and then searches for each word individually. You'll have to decide if this works for you or you can adapt it to better suit what you are looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest