1. 程式人生 > >利用selenium獲取cookies後,使用requests登陸獲取頁面

利用selenium獲取cookies後,使用requests登陸獲取頁面

import time
from selenium import webdriver
import requests
from lxml import html
from lxml import etree
import pickle
def getcookies():
driver = webdriver.Chrome(executable_path=r’C:\Python35\chromedriver.exe’)
driver.get(‘http://10.x.x.xx:80/‘)
time.sleep(1)
driver.find_element_by_id(‘username’).send_keys(‘azkaban’)
time.sleep(1)
driver.find_element_by_id(‘password’).send_keys(‘azkaban’)
time.sleep(1)
driver.find_element_by_id(‘login-submit’).click()
# time.sleep(2)
# driver.find_element_by_xpath(‘/html/body/div[2]/div/div[3]/ul[1]/li[4]’).click()
# time.sleep(3)
cookies = driver.get_cookies()
driver.close()
return cookies

def main():
get_cookies = getcookies()
#儲存cookies
pickle.dump(get_cookies, open(‘cookies.pkl’, ‘wb’))
cookies = pickle.load(open(‘cookies.pkl’, ‘rb’))
session_requests = requests.Session()
for cookie in cookies:
session_requests.cookies.set(cookie[‘name’], cookie[‘value’])
result = session_requests.get(“

http://10.x.x.xx:80/history?page=1&size=200“)
tree = etree.HTML(result.content.decode(‘utf-8’))
result1 = etree.tostring(tree)
print(result1.decode(“utf-8”))

if name == ‘main‘:
main()