BC25
BC25

Reputation: 11

How to find all the elements containing a certain text using xpath Selenium and Python

I tried

driver.find_elements_by_xpath("//*[contains(text()),'panel')]") 

but it's only pulling through a singular result when there should be about 25.

I want to find all the xpath id's containing the word panel on a webpage in selenium and create a list of them. How can I do this?

Upvotes: 1

Views: 4012

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

To collect all the elements containing a certain text e.g. panel using Selenium you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use the following Locator Strategy:

  • Using XPATH and contains():

    elements = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[contains(., 'panel')]")))
    
  • 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
    

Upvotes: 0

Mohima Chaudhuri
Mohima Chaudhuri

Reputation: 109

The xpath in your question has an error, not sure if it is a typo but this will not fetch any results. There is an extra parantheses.

Instead of :

driver.find_elements_by_xpath("//*[contains(text()),'panel')]") 

It should be :

driver.find_elements_by_xpath("//*[contains(text(),'panel')]") 

Tip: To test your locators(xpath/CSS) - instead of directly using it in code, try it out on a browser first. Example for Chrome:

  1. Right click on the web page you are trying to automate
  2. Click Inspect and do a CTRL-F.
  3. Type in your xpath and press ENTER

You should be able to scroll through all the matched elements and also verify the total match count

Upvotes: 1

Related Questions