Skip to content

Search for a specific element in multiple pages and click using Python Selenium

Hi im trying to navigate from page 1 to page 5 (the element can be in any of the pages)and find and click on a specific element using python selenium. The following is the element from the page:

<span _ngcontent-mtx-c123"" class"ng-star-inserted">ABC Company</span>

i tried by using : driver.find_element_by_name("ABC Company").click() but this doesnt work. Another Way i tried:

1. element_path="//span[contains(text(),'ABC Company')]" 
2. while True: 
3.  if(driver.find_elements_by_xpath(element_xpath)): driver.find_element_by_xpath(element_xpath).click() 
4.  else: driver.find_element_by_xpath("xpath to goto next page").click()

I need the code to find element from the next pages until its found and then click it.

is there any other way to do this???

Thanks in Advance



First, you need to check if the element is present and only if it does – click it. Otherwise you will get exception while trying clicking non-existing element.
driver.find_elements returns a list of web elements matching the passed locator. So if there are such elements it will return non-empty list interpreted as True by Python. Otherwise empty list is returned interpreted as False.
As about the locator for the element you are looking for: you can locate the element according to the text it contains. It can be done with XPath.
As following:

element_xpath = "//span[contains(text(),'ABC Company')]"

If you need to update the XPath locator dynamically you can pass the text as parameter. Let’s say you have a list of texts, you can iterate on them as following:

for txt in texts:
    element_xpath = "//span[contains(text(),'{}')]".format(txt)