Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element by href value using selenium python?

I have href value of an anchor tag which only have href value as attribute. Now I want to find the element in the page which have same value as my href value and click it. I am unable to find any way of doing this using standard selenium methods.How can I do this? Basically these are the functions I found but it seems that I can't use any of these:

find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
like image 886
user3870509 Avatar asked Oct 15 '15 18:10

user3870509


People also ask

How do I find the href of an element?

To identify the link with the href attribute we can take the help of the locators xpath or css selector. We shall use the findElement method and pass By. xpath or By. cssSelector as a parameter to this method.

How does Selenium find element by link?

We can find an element using the link text or the partial link text in Selenium webdriver. Both these locators can only be applied to elements with the anchor tag. The link text locator matches the text inside the anchor tag.

How does Selenium calculate href value?

We can fetch href links in a page in Selenium by using the method find_elements(). All the links in the webpage are designed in a html document such that they are enclosed within the anchor tag. To fetch all the elements having <anchor> tagname, we shall use the method find_elements_by_tag_name().


3 Answers

You can use find_element_by_xpath functionality.

driver.find_element_by_xpath('//a[@href="'+url+'"]')
like image 154
Dmytro Pastovenskyi Avatar answered Oct 15 '22 12:10

Dmytro Pastovenskyi


You can try this:

driver.find_element_by_xpath('//a[contains(@href,"href")]')
like image 30
Netra Shah Avatar answered Oct 15 '22 14:10

Netra Shah


You would find the element by the CSS selector, as you would using vanilla CSS:

link = driver.find_element_by_css_selector('[href^=http://somelink.com/]')

You can also find the element by the link text:

link = driver.find_element_by_partial_link_text('somelink')
like image 37
rnevius Avatar answered Oct 15 '22 12:10

rnevius