1 Question: Python Selenium - find element by link containing certain words

Question created on Tuesday March 20, 2018

I am running a code that navigates through folders and finally arrives at a destination and downloads a file by just clicking on it.

For example, to find a folder I am using:

find_element_by_link_text("Pricing and Catalogs")

The problem is that the folder sometimes isn't written exactly like that. For example, it has double spaces.

So my question is: is it possible to find an element by text that contains certain words? For example something like this (I know it's not correct, I just want you to understand me):

find_element_by_link_text(containing "Pricing" and "Catalogs")

I searched for the answer but couldn't find what I was looking for. If this is duplicated I apologize and ask to be pointed in the right direction.

Thanks in advance!

EDIT: Using find_element_by_partial_link_text won't do it since there are other folders with either Pricing or Catalogs in their names.

<td class="ms-tv-item ctl00_PlaceHolderLeftNavBar_ctl02_WebTreeView_2" style="white-space:nowrap;"><a class="ctl00_PlaceHolderLeftNavBar_ctl02_WebTreeView_0 ms-tv-item ctl00_PlaceHolderLeftNavBar_ctl02_WebTreeView_1" href="javascript:_spNavigateHierarchy(this,'','TAKES YOU TO SOME PAGE',false,'FolderNode', '')" title="Pricing  and  Catalogues" id="ctl00_PlaceHolderLeftNavBar_ctl02_WebTreeViewt223" style="border-style:none;font-size:1em;">Pricing  and  Catalogues</a></td>
3 answer                              3                         

You could try XPath:


find_element_by_xpath("//a[contains(text(), 'Pricing') and contains(text(), 'Catalogues')]")

EDIT You've misspelled link text. Code has 'Catalogs'. But HTML has 'Catalogues'. Corrected xpath.

Tuesday March 20, 2018

Also, replacing text with node sometimes works better:

Example of usage:

find_element_by_xpath("//a[contains(node(), 'Pricing') and contains(node(), 'Catalogs')]")
Tuesday March 20, 2018

To click on the intendeed element containing the texts Pricing and Catalogs you can use either of the following lines of code :


    WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.LINK_TEXT, "Pricing  and  Catalogues"))).click()
  • XPATH :

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(.,'Pricing') and contains(.,'Catalogs')]"))).click()

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.ctl00_PlaceHolderLeftNavBar_ctl02_WebTreeView_0.ms-tv-item.ctl00_PlaceHolderLeftNavBar_ctl02_WebTreeView_1[title='Pricing  and  Catalogues']"))).click()
Tuesday March 20, 2018
source posted here