gpt4 book ai didi

python - 用selenium python模拟一个onclick

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:49 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com