Home > Blockchain >  How can I locate an element with specific text in it?
How can I locate an element with specific text in it?

Time:04-06

enter image description here

The label is the element I'm trying to locate, and the text I know is Cost of paving parking lot in front of building.

I tried contains, innerText(), and textContent()

CodePudding user response:

The following xpath should match all label elements that have descendant node with tag p containing your text. Try if it works for your problem.

label_elem = driver.find_element_by_xpath("//label[.//p[contains(text, 'Cost of paving parking lot in front of building.')]]")

CodePudding user response:

To locate the with respect to the <p> element containing the text Cost of paving parking lot in front of building you can use either of the following locator strategies:

  • Using XPATH with respect to <p> tag:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//p[contains(., 'Cost of paving parking lot in front of building')]//ancestor::label[@class='ahe-ui-radio']")))
    
  • Using XPATH with respect to child tags:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//label[@class='ahe-ui-radio' and @for][.//p[contains(., 'Cost of paving parking lot in front of building')]]")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • Related