Selenim 是一個自動化測試工具,能夠利用它驅動瀏覽器執行特定的動做,如點擊、下拉等操做,同時能夠獲取瀏覽器當前呈現的頁面的源代碼,作到可見及可爬css
1.使用流程html
1)聲明瀏覽器對象python
Selenium 支持很是多的瀏覽器,如Chrome、Firefox、Edge等,還有Android、BlackBerry等手機端瀏覽器。web
2)訪問頁面api
能夠經過get()方法來請求網頁,參數傳入連接URL便可。瀏覽器
3)查找節點cookie
Selenium 能夠驅動瀏覽器完成各類操做,好比填充表單、模擬點擊等。ide
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
如要獲取多個節點,element改成elements
4)節點交互工具
Selenium能夠驅動瀏覽器來執行一血操做,也就是說能夠讓瀏覽器模擬執行一些動做。比較常見的用法有:輸入文字時用send_keys()方法,清空文字時用clear()方法,點擊按鈕時用click()方法測試
更多操做可見 http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement
5)動做鏈
鼠標拖曳、鍵盤按鍵等
ActionChains http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains
6)執行JavaScript
調用execute_script()方法便可,傳入參數爲js方法
7)獲取節點信息
獲取屬性 .get_attribute()
獲取文本值 .get_text()
獲取id、位置、標籤名和大小
.id .location .tag_name .size
8)切換Frame
switch_to.frame()
Selenium打開頁面後,默認在父級Frame中進行操做,若是頁面中存在子Frame,則不能獲取到子Frame中的節點
9)延時等待
隱式等待
若是Sekenium沒有在DOM中找到節點,將繼續等待,超出設定時間後,則拋出找不到節點的異常。
.implicitly_wait()
顯式等待
指定要找到的節點,而後指定一個最長等待時間。若是在規定時間內加載出來了這個節點,就返回查找的節點;若是到了規定時間依然沒有加載出該節點,則拋出異常
WebDriverWait().until(expected_conditions.presence_of_element_located(()))
10)Cookies
使用Selenium,能夠方便地對Cookies進行操做
.get_cookies() 獲取cookie
.add_cookie() 添加cookie
.dele_all_cookies() 刪除全部cookie