问题
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:
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()
回答2:
Use the following code for that:
br.find_element_by_link_text("Fastener").click()
Hope it helps you!
回答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")
回答4:
Use contains to search element
//a[contains (@onclick='fastener')]
OR
//a[contains(text(),"Fastener")]
来源:https://stackoverflow.com/questions/49171370/python-selenium-how-can-click-on-onclick-elements