用硒python模拟onclick [英] simulate a onclick with selenium python
问题描述
我对硒还很陌生,我正在尝试弄清楚如何模拟onclick
I am pretty new to selenium and I am trying to figure out how to simulate a onclick
这是我在检查html源代码时在源代码中看到的内容
this is what I see in the source code when I inspect the html source
<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代码,对吧?
Meaning you can execute Javascript code just by using .execute_script , Awesome, right?
无效的InvalidSelectorException
是在没有任何元素或没有经验的情况下提出的,可能会有一个iframe,并且您必须使用.switch_to.frame
才能与之交互.
另外,我喜欢使用XPath(始终最可靠),习惯它需要一点时间,但是经过一两个小时的练习就可以掌握它.
An invalid InvalidSelectorException
is an expecting raised when there's no element or from experience, there could be an iframe and you'll have to use .switch_to.frame
to be able to interact with it.
Also, I like using XPath (most reliable always), it takes a little bit time getting used to, but with an hour or two of practising you can get it.
JeffC有一个优点,HTML,JS的结构可以随时更改.
您可以使用find_element_by_xpath(xpath).click()
,但还有其他更动态的方法来预测结构是否会发生变化,例如使用find_element_by_name
或其他可用的
JeffC has a good point, the structure of the HTML, JS can always change.
You can use the find_element_by_xpath(xpath).click()
but there are also more dynamic ways to predict wether the structure is going to change, using something like find_element_by_name
or other that are available:
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模拟onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!