Splinter入门(九) Matchers 匹配器
我们知道,现在的网站基本都是动态网站,即采用了AJAX
和异步JavaScript
,因而很多元素标签都不会呈现在HTML
中,是通过JavaScript
动态创建的。在这种情况下,可以采用is_element_present
和 is_text_present
去check是否某个元素或者文本是否存在。在这种情况下,Splinter
或加载HTML
和JavaScript
代码,并做check,这个check是在JavaScript响应之前做的!!
对于is_element_present
和 is_text_present
可以传递wait_time
参数(延时时间:单位s
),如果存在,上述方法返回True
(即使还没超过延时时间),如果直到延时时间结束都没有check到,则返回False
。
检验text是否存在
is_text_present
用于检测text是否存在,存在则返回True
,不存在返回False
。例如:
browser = Browser()
browser.visit('https://splinter.readthedocs.io/')
browser.is_text_present('splinter') # True
browser.is_text_present('splinter', wait_time=10) # True, using wait_time
browser.is_text_present('text not present') # False
is_text_not_present
用于检测text是否存在,不存在则返回True
,存在返回False
。例如:
browser = Browser()
browser.visit('https://splinter.readthedocs.io/')
browser.is_text_not_present('text not present') # True
browser.is_text_not_present('text not present', wait_time=10) # True, using wait_time
browser.is_text_not_present('splinter') # False
检验Elements(元素)是否存在
Splint提供了6种方法来检查页面中是否存在元素,每个选择器类型都有一个:css
, xpath
, tag
, name
, id
, value
, text
。is_element_present_by*
方法表示存在则返回True
,不存在返回False
。例如:
browser.is_element_present_by_css('h1')
browser.is_element_present_by_xpath('//h1')
browser.is_element_present_by_tag('h1')
browser.is_element_present_by_name('name')
browser.is_element_present_by_text('Hello World!')
browser.is_element_present_by_id('firstheader')
browser.is_element_present_by_value('query')
browser.is_element_present_by_value('query', wait_time=10) # using wait_time
is_element_not_present_by*
方法表示不存在则返回True
,存在返回False
。例如:
browser.is_element_not_present_by_css('h6')
browser.is_element_not_present_by_xpath('//h6')
browser.is_element_not_present_by_tag('h6')
browser.is_element_not_present_by_name('unexisting-name')
browser.is_element_not_present_by_text('Not here :(')
browser.is_element_not_present_by_id('unexisting-header')
browser.is_element_not_present_by_id('unexisting-header', wait_time=10) # using wait_time
检验Elements(元素)是否可见
HTML
中,元素可以设置hidden
属性,用于控制元素是否可见。上面所说的present
表示元素是否存在,这两个是不同的概念。is_element_visible*
用于check元素是否可见,提供了css
和xpath
两种选择器。如果可见则返回True
,不可见返回False
。例如:
browser.is_element_visible_by_css('h5')
browser.is_element_visible_by_css('h5', wait_time=10)
browser.is_element_visible_by_xpath('//h5')