用Selenium Python模拟一个单击



我对硒是非常新的,我正在尝试弄清楚如何模拟onclick

这是我检查HTML源

时在源代码中看到的内容
<a href="#" onclick="document.getElementById('pN').selectedIndex = 0;document.getElementById('optionList').submit();return false"> <img src="images/ListingOptionSearch.jpg" onmouseover="this.src='images/ListingOptionSearchHover.jpg'" onmouseout="this.src='images/ListingOptionSearch.jpg'"> </a>

我尝试了:

driver.find_element_by_css_selector("a[onlick*=document.getElementById('pN')
.selectedIndex]").click()

但我得到了InvalidSelectorException

有什么想法吗?

谢谢!

您可以使用

from selenium import webdriver
browser = webdriver.Chrome(somepath) # You should know what this does.
browser.execute_script("document.getElementById('pN').selectedIndex = 0;document.getElementById('optionList').submit();return false")

意味着您只需使用.execute_script,真棒,对吗?

,您可以执行JavaScript代码

无效的InvalidSelectorException是当没有元素或经验的情况下,可能会提出一个期望,可能会有一个iFrame,您必须使用.switch_to.frame才能与之互动。另外,我喜欢使用XPath(总是最可靠的(,需要一点时间来习惯,但是有了一两个小时的练习,您就可以得到它。

jeffc有一个很好的观点,html的结构总是可以改变。您可以使用find_element_by_xpath(xpath).click(),但也有更多动态的方法可以预测结构是否会改变,例如find_element_by_name或其他可用的东西

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

您是否Google Google google例外了?这意味着您的选择器无效。CSS选择器(例如您要使用的一个(以tag[attribute='value']表格。您没有引号包围的价值...在这种特定情况下,这是不可能的,因为您的价值已经包含单语引号。

由于A标签包含IMG标签,因此您可以单击IMG标签并获得相同的效果。CSS选择器如下所示。

img[src='images/ListingOptionSearch.jpg']

还有其他选择器可能会起作用,但是有指向页面的链接等。我只是猜测它们是否是唯一的。

最新更新