使用selenium python模拟onclick

时间:2017-04-20 23:45:31

标签: 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

任何想法?

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用

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

答案 1 :(得分:1)

你有谷歌例外吗?这意味着您的选择器无效。像您尝试使用的CSS选择器采用tag[attribute='value']形式。您没有被引号括起来的值...在这种特定情况下,这是不可能的,因为您的值已包含单引号。

由于A标记包含IMG标记,因此您可以单击IMG标记并获得相同的效果。像下面这样的CSS选择器应该可以工作。

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

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