平臺:machtml
網站:人人網web
最近練習爬蟲登錄,方法一是找頁面裏的js文件,經過解析js文件找到cookie信息再保持。但如今的站點登錄都有驗證碼,並且最煩的是request時data表單裏的值基本上沒有不加密的,js學的很差,就別想着破解了。因此想起了用的比較少的selenium模塊,用於模擬登錄並獲取cookie。chrome
import time,random from selenium import webdriver import requests from urllib import request from lxml import etree driver = webdriver.Chrome(executable_path=r'/Applications/Google Chrome.app/chromedriver') driver.get('http://www.renren.com/PLogin.do') time.sleep(2) driver.find_element_by_id('email').clear() driver.find_element_by_id('email').send_keys('myusername') # 輸入用戶名 driver.find_element_by_id('password').clear() driver.find_element_by_id('password').send_keys('mypassword') # 輸入密碼 img_url = 'http://icode.renren.com/getcode.do?t=web_login&rnd='+str(random.random()) request.urlretrieve(img_url,'renren_yzm.jpg') try: driver.find_element_by_id('icode').clear() img_res = input('輸入驗證碼:') # 若是須要輸入驗證碼,能夠手工,或者接口給打碼平臺 driver.find_element_by_id('icode').send_keys(img_res) except: pass driver.find_element_by_id('autoLogin').click() # 自動登錄 driver.find_element_by_id('login').click() # 登錄 time.sleep(3) cookie_items = driver.get_cookies() # 獲取cookie值 post = {} # 保存cookie值 for cookie in cookie_items: post[cookie['name']] = cookie['value'] print(post['t']) # 人人網登錄後須要保持登錄的cookie信息 driver.quit() # 退出selenium # ------------------------------------------------------------ url = 'http://www.renren.com/265025131/profile' headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', 'Cookie':'t='+post['t'], } response = requests.get(url,headers=headers) print('-'*50) html = etree.HTML(response.text) title = html.xpath('//title/text()') print('目前獲得的頁面信息',title) print(response.url)
總結:使用selenium模擬登錄、獲取cookie沒用多少時間,但想固然的覺得進入renren的我的頁面必須使用獲取的全部cookie值,徒浪費N多個小時,結果只保留了cookie內的't'值,就作到保持登錄,因此,不斷的測試,是比較重要的。cookie