Python Splinter 点击按钮 CSS
我在用Splinter脚本选择一个按钮时遇到了麻烦,使用的是find_by_css
这个方法。文档里的信息很少,我也没找到很多好的文章来举例说明。
br.find_by_css('div#edit-field-download-files-und-0 a.button.launcher').first.click()
...这里的br
是我的浏览器实例。
我试过几种不同的写法,但我真的不确定该怎么做,因为文档里没有给出具体的语法例子。
这是我想操作的元素的截图。
抱歉,截图效果不是很好。
有没有人有这方面的经验?
3 个回答
我喜欢W3Schools提供的CSS选择器参考资料:http://www.w3schools.com/cssref/css_selectors.asp
关于你的代码……我建议你把它分成几个步骤来处理,特别是在调试的时候。调用br.find_by_css('css_string')会返回一个元素的列表。所以你可以先获取这个列表,然后检查一下里面有多少个元素。
elems = br.find_by_css('div#edit-field-download-files-und-0 a.button.launcher')
if len(elems) == 1:
elems.first.click()
如果你不检查返回的列表长度,就直接在一个空列表上调用'.first',那就会出错。如果长度大于1,你可能会得到一些意想不到的东西。
每个页面上的id都是唯一的,你可以串联搜索,所以可以用几条不同的语句来实现这个功能:
id_elems = br.find_by_id('edit-field-download-files-und-0')
if id_elems:
id_elem = id_elems.first
a_elems = id_elem.find_by_tag("a")
for e in a_elems:
if e.has_class("button launcher"):
print('Found it!')
e.click()
当然,这只是实现这个功能的众多方法之一。最后,Splinter是一个封装了Selenium和其他网页驱动的工具。即使你找到了要点击的元素,实际点击可能也不会有任何反应。如果发生这种情况,你还可以尝试点击封装的Selenium对象,那个对象可以通过e._element来访问。所以如果需要的话,你可以尝试e._element.click()。
我正在做一个类似的事情,想要在网页上点击一些东西。关于 find_by_css() 的说明非常简陋,你需要输入你想点击的元素的 CSS 路径。

假设我们想去 python.org 的关于标签。
from splinter import Browser
from time import sleep
with Browser() as browser: #<--Create browser instance (firefox default driver)
browser.visit('http://www.python.org') #<--Visits url string
browser.find_by_css('#about > a').click()
# ^--Put css path here in quotes
sleep(5)
如果你的网络连接很好,你可能看不到关于标签被点击的过程,但最终你应该会到达关于页面。
最难的部分是找出一个元素的 CSS 路径。不过,一旦你找到了,使用 find_by_css()
方法就显得很简单了。
这个CSS选择器看起来没问题,只是我不太确定你是从哪里找到find_by_css
这个方法的?
那这样怎么样呢:
br.find_element_by_css_selector("div#edit-field-download-files-und-0 a.button.launcher").click()
Selenium提供了以下方法来定位页面中的元素:
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
要找到多个元素(这些方法会返回一个列表):
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector