python - 用selenium python模拟一个onclick

标签 python selenium selenium-webdriver web-scraping

我是 selenium 的新手,我正在尝试弄清楚如何模拟 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 的结构,JS 总是可以改变的。 您可以使用 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

关于python - 用selenium python模拟一个onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531654/

相关文章:

python - 使用 astropy.io.fits 编写拟合文件

Java - Selenium(chrome 驱动程序)元素不可见异常

java - 等待元素的可见性

java - 如何使用 Selenium 读取pdf文件

Python 从属性移动到他的类

python - 字符串到字典 Python

python - 通过 Selenium 和 Webdriver 循环遍历 find_element_by_xpath() 的元素列表

java - Selenium 在线游戏自动化

javascript - 如何检查 JavaScript 文件是否尚未加载或正在加载

python - 为什么 class_weights 不起作用并出现错误?