简体   繁体   中英

Finding text in element with selenium python

I am wanting to state whether this text 'Awaiting Review' is true or not. How do I find this element? With all the parent elements im struggling to get it. If someone could elaborate on how it works that would be amazing. 在此处输入图片说明

Since you're in DevTools, you can right click and select 'Copy XPath'. This will give you a specific and unique selector for the element so you don't need to worry about counting parent divs all the way from the root! Learning XPaths is a great tool, see here: https://www.w3schools.com/xml/xpath_syntax.asp

Then in your Selenium code you can write:

awaiting_review = driver.find_element_by_xpath('# paste xpath here').text

if awaiting_review == 'Awaiting Review':
   # whatever you want to happen

Explanation :- with //span[contains(text(), 'Awaiting Review')] you can located the element and can check if the size if > 0 using find_elements , if it is, then you can assert, (I am just using print) and if it's not, code will go to else part.

You can try with below code :

try:
   if len(driver.find_elements(By.XPATH, "//span[contains(text(), 'Awaiting Review')]")) > 0 :
       print("Awaiting Review is present")
   else:
        print("Awaiting Review is not present")
except:
    print("something went wrong. ")
    pass

Update 1 :

try:
   if len(driver.find_elements(By.CSS_SELECTOR, "div#air-pipeline-board heade.air-pipeline-lane span")) > 0 :
       print("Awaiting Review is present")
   else:
        print("Awaiting Review is not present")
except:
    print("something went wrong. ")
    pass

To simply validate if element containing that text exists on the page you can do this:

if driver.find_elements(By.XPATH, "//span[contains(text(), 'Awaiting Review')]"):
    print("Element is presented")
else:
    print("Eelement not found")

driver.find_elements returns a list of elements matching the passed locator.
So if there is a span element containing Awaiting Review text is presented on the page it will return it. Otherwise it will return an empty list.
Non-empty list is seen as True by Python while empty list is False .

Please try this.

elems = driver.find_elements_by_css_selector("#vacancy-pipeline-header>header>div>span")
if elems:
   if elems[0].text == "Awaiting Review":
     print('valid!')
   else 
     print('invalid!')
else
  print('Element is not exist!')

If you are familiar with CSS selector, it's good for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM