3

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.

1
  • @onlick is an XPath syntax. In CSS you should use a[onlick*='fastener'] Commented Mar 8, 2018 at 11:46

4 Answers 4

5

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()
    
Sign up to request clarification or add additional context in comments.

Comments

1

Use the following code for that:

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

Hope it helps you!

Comments

1

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

Comments

0

Use contains to search element

//a[contains (@onclick='fastener')]

OR

   //a[contains(text(),"Fastener")]

1 Comment

I got the following error with both your suggestions: selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified

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.