clasico90
clasico90

Reputation: 57

Python Selenium - find element by link containing certain words

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>

Upvotes: 1

Views: 2522

Answers (3)

Alexey Dolgopolov
Alexey Dolgopolov

Reputation: 700

You could try XPath:

Example:

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.

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193228

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

  • LINK_TEXT :

    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()
    
  • CSS_SELECTOR :

    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()
    

Upvotes: 0

Coding Hobo
Coding Hobo

Reputation: 21

Also, replacing text with node sometimes works better:

Example of usage:

find_element_by_xpath("//a[contains(node(), 'Pricing') and contains(node(), 'Catalogs')]")

Upvotes: 1

Related Questions