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')