30

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

6 Answers 6

59

You can use find_element_by_xpath functionality.

driver.find_element_by_xpath('//a[@href="'+url+'"]')
Sign up to request clarification or add additional context in comments.

4 Comments

What if I have my url in a variable?
than just add it as a string there.
keep in mind that you might get an array returned if you have more than one link with the same URL
This works very well, as long as the page has loaded all the contents
15

You can try this:

driver.find_element_by_xpath('//a[contains(@href,"href")]')

Comments

8

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

Comments

4

When the button looks like

<a href="server_export.php" class="tab">&nbsp;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.

Comments

1

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

Comments

0

In versions 4 and later of Selenium, use find_element() combined with a CSS selector and the By class:

from selenium import webdriver
from selenium.webdriver.common.by import By

jobs_link = driver.find_element(By.CSS_SELECTOR, "[href='https://www.linkedin.com/jobs/?']")
jobs_link.click()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.