我在使用find_by_css
方法选择Splinter脚本中的按钮时遇到问题。文档最多是稀疏的,我没有找到很多带有示例的好文章。
br.find_by_css('div#edit-field-download-files-und-0 a.button.launcher').first.click()
...其中br
是我的浏览器实例。
我尝试过几种不同的写作方式。我真的不确定我应该怎么做,因为文档没有给出语法的任何硬性例子。
这是元素的截图。
抱歉屏幕截图很糟糕。
有没有人有这方面的经验?
答案 0 :(得分:3)
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
答案 1 :(得分:1)
我正在尝试点击类似的内容,我正在尝试点击网页上的内容。 find_by_css()的文档非常差,您需要键入要单击的元素的css路径。 假设我们想要访问python.org上的about选项卡
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()
方法看起来很容易
答案 2 :(得分:0)
我喜欢W3Schools对CSS选择参数的参考:http://www.w3schools.com/cssref/css_selectors.asp
至于你的代码...我建议将其分解为几个步骤,至少在调试期间。对br.find_by_css(&#39; css_string&#39;)的调用返回元素列表。所以你可以抓住那个列表并查看计数。
elems = br.find_by_css('div#edit-field-download-files-und-0 a.button.launcher')
if len(elems) == 1:
elems.first.click()
如果您不检查返回列表的长度,请致电&#39; .first&#39;在空列表中,您将获得例外。如果len> 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和其他webdrivers的包装器。有可能的是,即使您找到要点击的元素,实际的点击也不会做任何事情。如果发生这种情况,您还可以尝试单击包装的Selenium对象,该对象可用作e._element。所以你可以在必要的时候尝试e._element.click()。