Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Selenium to select an anchor with specific content

I have a HTML element as follows:

<a class="country" href="/es-co">
    Columbia
</a>

How do I select that anchor element based on the content 'Columbia'? I can't use find_element_by_class_css_selector because a.country represents half a dozen elements. How do I select that element and click it using Silenium with Python (through IE, if that has any bearing)?

As an aside, I could have any number of links with the same text and CSS selectors. How would Silenium differentiate?

like image 678
Nanor Avatar asked Sep 03 '25 02:09

Nanor


1 Answers

There's no find_element_by_class_css_selector. But you are right, you can't use class names.

The best way is to use href="/es-co", if it's unique.

find_element_by_css_selector("a[href='/es-co']")

Otherwise you can find by text using XPath

find_element_by_xpath(".//a[contains(text(), 'Columbia')])

If you have many links with same locator, then you can index them, either by XPath directly or the list returned by Selenium.

For example, if you have ten Columbia

find_element_by_xpath(".//a[contains(text(), 'Columbia')][10]") # one-based index, one element only
find_elements_by_xpath(".//a[contains(text(), 'Columbia')]")[9] #  find_elements_* gives you zero-base index list
like image 127
Yi Zeng Avatar answered Sep 04 '25 14:09

Yi Zeng