'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
Solution 1:[1]
You can try this:
driver.find_element_by_xpath('//a[contains(@href,"href")]')
Solution 2:[2]
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')
Solution 3:[3]
I have a button called Your Profile with this html line
<a href="/registration/profile.html" rel="follow">Your Profile</a>
I have been trying everything so far find_element_by link, xpath, css selector with no luck. It returns error unable to find the element.
browser.find_element_by_partial_link_text("Your Profile")
browser.find_element_by_xpath('//a[contains(@href,"registration/profile.html")]')
Thanks
Solution 4:[4]
When the button looks like
<a href="server_export.php" class="tab"> Export</a>
and because possibly the text is translated, we cannot use the search for the text Export, so we have to search e.g. for server_export within the href and can e.g. click it with
driver.find_element(By.XPATH,'//a[contains(@href,"server_export")]').click()
Note: Using the recommended find_element(By.xxxxx, ...) format.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Duck Dodgers |
| Solution 2 | rnevius |
| Solution 3 | Daniel |
| Solution 4 | Tom Kuschel |
