Selenium Python:如何根据 "onclick" 文本点击 <a> 标签

Selenium Python: How to click on a <a> tag based on "onclick" text

所以这个页面有几个

<a href="#" onclick="showpage('potato.php');">...
<a href="#" onclick="showpage('carrots.php');">...
<a href="#" onclick="showpage('chicken.php');">...
<a href="#" onclick="showpage('fish.php');">...

这些标签。虽然我可以做一个find_elements_by_xpath然后选择我想要的那个,有没有办法具体说一下,我想点击土豆link?

您可以使用 find_element_by_partial_link_text:

driver.find_element_by_partial_link_text("potato").click()

此处提供有关按策略查找的更多文档:http://selenium-python.readthedocs.org/en/latest/locating-elements.html

编辑:说说看错题了。我以为您要单击带有文本 "potato".

的 link

如果您专门尝试查找 onclick 的内容,您可以使用如下内容:

driver.find_element_by_xpath("//a[contains(@onclick, 'potato.php')]").click()

Richard 的解决方案应该有效。你也可以使用像

这样的 xpath
//a/*[contains(text(),'Potato')]