爬蟲
第六天
selenium
本次代碼需要用到插件Chromedriver,安裝方法
selenium 入門
pip install selenium
from selenium import webdirver
# 創建一個Chrome的driver實例對象
driver = webdriver.Chrome()
# 訪問人人登錄頁面
driver.get(url = "http://www.renren.com/")
# 填寫用戶名和密碼
driver.find_element_by_id("email").send_keys("xxx")
driver.find_element_by_id("password").send_keys("xxx")
# 點擊登陸
driver.find_element_by_id("login").click()
# 退出
driver.quit()
driver.page_source
網頁源碼driver.current_url
當前網頁的url
selenium處理cookie
通過driver.get_cookies()
能夠獲取所有的cookie
# 把cookie轉化爲字典
{cookie['name']: cookie['value'] for cookie in driver.get_cookies()}
#刪除一條cookie
driver.delete_cookie("CookieName")
# 刪除所有的cookie
driver.delete_all_cookies()
selenium定位元素
# 通過xpath定位元素
driver.find_element_by_xpath("//a")
# 通過鏈接文字定位
driver.find_element_by_link_text("下一頁")
# 通過包含得鏈接文字定位元素
driver.find_element_by_partial_link_text("下一")
# 通過標籤名定位
driver.find_element_by_tag_name("a")
- find_element 返會一個Element對象,如果沒找到,報錯
- find_elements 返回一個列表,元素項時Elements,如果沒找到,返回空列表
find_element_by_xpath() 或者find_element_by_xpath()中傳入得xpath表達式只能定位到標籤
,如果需要獲取指定element的文本或者屬性值:
- elelemt.text 獲取文本
- element.get_attribute("") 獲取屬性內容
切換iframe
網頁存在iframe嵌套架構,如果要查找的標籤在指定的iframe裏面,必須先切換到iframe中才能正確找到
driver.switch_to.frame()
可以傳入iframe的id、name、element對象
驗證的判斷
flask的項目中的驗證碼邏輯:
- 前端js產生一個UUID,發起圖片驗證碼請求時帶上UUID參數
- 後端隨機生成一個code,以UUID:code的形式存入Redis數據庫中
- 前端POST請求提交驗證時,需要攜帶UUID,後端從redis中讀取指定的code和用戶輸入的進行對比驗證
傳統的驗證碼請求方式:
- 請求網頁登陸頁面的時候,服務器爲當前用戶開闢session空間,並向瀏覽器的cookies中寫入一個seesion_id
- 瀏覽器請求驗證碼驗證碼圖片時會自動攜帶cookies,seesion_id 會被提交到服務器 ,後端產生隨機的code 放入sesion_id指定的sesion空間中
- 前端發起提交驗證的 post請求時,也會自動攜帶cookie,seesion_id 會再次被提交到服務器 ,後端根據session_id在指定的sesion空間中找出曾經存入的code,和前端提交的進行對比驗證
此種情況下,應考慮使用requests.session()
來進行驗證碼突破