在使用requests時,因為有的網站需要登錄驗證碼,而我們又不能通過驗證碼識別程序,那么這個時候就要借助selenium手動登錄,然后獲取cookie共享給requests使用。
1.在未登錄的情況下,使用requests爬取我們想要的東西
# -*- coding:utf-8
import requests def crawler(): sess = requests.Session() url = 'http://210.74.4.127:8888/jes/jptInputInvoiceQuery.ajax?ssId=JPT&_dc=1564026411786' data = {'page': 1, 'start': 0, 'limit': 10} html = sess.post(url, data).text print(html) if __name__ == "__main__": crawler()
運行后發現需要登錄:
但是由於頁面有驗證碼,只能通過selenium獲取cookie,然后共享給requests使用:
#!/usr/bin/env python # -*- encoding: utf-8 -*- from selenium import webdriver import requests import time def getCookies(): # 設置瀏覽器默認存儲地址 options = webdriver.ChromeOptions() # options.add_argument('--headless') driver = webdriver.Chrome(options=options) driver.maximize_window() driver.get("http://210.74.4.127:8888/jes/login.html") # 輸入用戶名 driver.find_element_by_id("userId").send_keys("cheng") # 輸入密碼 driver.find_element_by_id("password").send_keys("admin123") # 等待拖拽驗證碼 time.sleep(10) # 點擊提交 driver.find_element_by_css_selector("input.log_button").click() # 獲取cookie cookies = driver.get_cookies() driver.close() return cookies def crawler(): sess = requests.Session() sess.headers.clear() # 將selenium的cookies放到session中 for cookie in getCookies(): sess.cookies.set(cookie['name'], cookie['value']) url = 'http://http://210.74.4.127:8888/jes/jptInputInvoiceQuery.ajax?ssId=JPT&_dc=1564026411786' data = {'page': 1, 'start': 0, 'limit': 10} html = sess.post(url, data).text print(html) if __name__ == "__main__": crawler()
運行結果: