Python + Selenium: How can click on "onclick" elements?

13,580

Solution 1

To search the element with text as Fastener you can use either of the following options :

  • Through Fastener :

    br.find_element_by_link_text("Fastener").click()
    
  • Using onclick through fastener (xpath):

    br.find_element_by_xpath("//a[contains(@onclick,'fastener')]").click()
    
  • Using onclick through fastener (css_selector):

    br.find_element_by_css_selector("a[onclick^='fastener']").click()
    

Solution 2

Use the following code for that:

br.find_element_by_link_text("Fastener").click()

Hope it helps you!

Solution 3

Using capybara-py:

page.click_link("Fastener")

Capybara is designed to provide this and many other similar helper methods, such as one might need to write acceptance tests from the perspective of end users:

page.fill_in("Street", value="123 Main St")
page.select("United States", field="Country")
page.choose("Expedited shipping")
page.click_button("Place order")
Share:
13,580

Related videos on Youtube

kksagar
Author by

kksagar

Trying to balance the elegance of applied mathematics with the reality of engineering. Fan of open source software, though I haven't yet contributed.

Updated on June 04, 2022

Comments

  • kksagar
    kksagar about 2 years

    I have an "onclick" element in a webpage whose HTML reads as follows:

    <a href="#" onclick="fastener('3625')">Fastener</a>
    

    I want to search this element using the string "fastener" or "Fastener" using Python + Selenium. The number "3625" will change depending on previous inputs, and hence cannot be searched for.

    I tried the following, but in vain:

    br.find_element_by_css_selector("a[@onlick*='fastener']").click()
    

    Please suggest ways to do this. Thank you!

    P.S.: I am using Python 2.7, with Chrome WebDriver and Chrome v62.

    • Andersson
      Andersson over 6 years
      @onlick is an XPath syntax. In CSS you should use a[onlick*='fastener']
  • kksagar
    kksagar over 6 years
    I got the following error with both your suggestions: selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified