Find if text exist inside a nested Div, if yes print out the whole string, Selenium Python

Viewed 34

i'm very new to selenium(3.141.0) and python3, and i got a problem that couldn't figure it out.

The html looks similar to this

<div class='a'>
   <div>
     <p><b>ABC</b></p>
     <p><b>ABC#123</b></p>
     <p><b>XYZ</b></p> 
   <div>
</div>

I want selenium to find if # exist inside that div, (can not target the paragraph only element because sometime the text i want to extract is inside different element BUT it's always inside that <div class='a'>) If # exist => print the whole <p><b>ABC#123</b></p> (or sometime <div>ABC#123<div> )

1 Answers

To find an element with contained text, you must use an XPath. From what you are describing, it looks like you want the locator

//div[@class='a']//*[contains(text(),'#')]
^ a DIV with class 'a'
                 ^ that has a descendant element that contains the text '#' within itself or a descendant

The code would look something like

for e in driver.find_elements(By.XPATH, "//div[@class='a']//*[contains(text(),'#')]"):
    print(e.get_attribute('outerHTML')

and it will print all instances of <b>ABC#123</b>, <div>ABC#123</div>, or <p>ABC#123</p>, whichever exists

Related