獲取cookie的幾種方式


 

在爬蟲中cookie是非常有用的,可以解決反爬,封號等問題。接下來我們來說說獲取cookie的集中方式。

這里采用python2.7,本來我都是用python3.6的,來了公司之后,公司適用版本2.7,就2.7咯,反正就寫法上面有一些區別

 

第一種:mechanize

首先我們要使用mechanize,第一步:

pip install mechanize

 

第二步編寫獲取cookie代碼:

import os
import mechanize
import cookielib,re

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.set_debug_http(True)

br.addheaders = [('User-agent', '用戶ua')]
br.set_proxies({"http": "代理"})
response = br.open('https://www.amazon.com')



cj = br._ua_handlers['_cookies'].cookiejar
for cookie in cj:
    print("cookieName:"+cookie.name)
    print("cookieValue:"+cookie.value)

cookie = [item.name + ":" + item.value for item in cj]
cookiestr={}
for item in cookie:
    name,value = item.split(":")
    cookiestr[name]=value

運行結果:

 

第二種:urllib

import urllib2
import cookielib
from http import cookiejar
from bs4 import BeautifulSoup

User_Agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
header = {}
header['User-Agent'] = User_Agent

cookie = cookiejar.CookieJar()
cookie_handle=urllib2.HTTPCookieProcessor(cookie)
cookie_opener = urllib2.build_opener(cookie_handle)

# proxy_support = urllib2.ProxyHandler({"http":"5.62.157.47:8085"})
# proxy_opener = urllib2.build_opener(proxy_support)

urllib2.install_opener(cookie_opener)
# urllib2.install_opener(proxy_opener)

request = urllib2.Request("https://www.amazon.com",headers=header)
response = urllib2.urlopen(request)

for item in cookie:
    print('Name = ' +item.name)
    print('Value =' +item.value)

運行結果:

 

第三種:requests

import requests
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
r = requests.get('https://www.amazon.com', headers = headers)
for cookie in r.cookies:
    print(cookie.name)
    print(cookie.value)
    print("=========")

 

運行結果:

 

 

 

第四種:selenium(個人感覺這個雖然加載比較慢,但是獲取cookie最全)

pip install selenium

代碼:

from selenium import webdriver
driver = webdriver.Chrome(executable_path='d:/seop/chromedriver.exe')
driver.get("https://www.amazon.com")
#for c in cookiestr.keys():
#    driver.add_cookie({'name':c,'value':cookiestr[c]})

#driver.get("https://www.amazon.com")

cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
cookiestr = ';'.join(item for item in cookie)

運行結果:

 

第五種:總覺得selenium比較慢,打開還要加載瀏覽器,於是嘗試了 htmlunit以及phantomjs

htmlunit

 

 phantomjs

from selenium import webdriver
browser = webdriver.PhantomJS()
browser.get("https://www.amazon.com")
cookie = [item["name"] + "=" + item["value"] for item in browser.get_cookies()]
cookiestr = ';'.join(item for item in cookie)

運行結果:

 

第六種:scrapy 

這邊我們簡單測試一下,首先你電腦已經要安裝了scrapy,如果沒有安裝,pip install scrapy

然后我們輸入要獲取地址的cookie

scrapy shell "https://www.amazon.com"

cookie結果:

 

 

 最后一種:chrome headless 使用無頭瀏覽器來獲取

這個目前我是在centos上面進行操作:

第一步:肯定你要安裝chrome啦

第二步:運行安裝腳本

curl https://intoli.com/install-google-chrome.sh | bash  

測試是否成功: 運行以下命令,如果成功會在當前目錄下面保存百度的截圖

google-chrome-stable --no-sandbox --headless --disable-gpu --screenshot     https://www.baidu.com  

 

這里我們開始獲取cookie信息

first:

google-chrome-stable --no-sandbox --headless --disable-gpu --user-data-dir="$HOME/Library/Application Support/Google/Chrome/" --remote-debugging-port=9222  https://www.amazon.com

 

second: 這里我們主要是獲取websocket的url

curl -s localhost:9222/json 

 

 third: 這邊要注意哦,要安裝wsc,安裝wsc之前記得要安裝npm哦,然后在執行npm install -g wsc,然后在執行以下命令

wsc ws://localhost:9222/devtools/page/D42AFC3C9AF9C8A1511ADC60850BD5A8

然后輸入:

{"id": 1, "method": "Network.getAllCookies"}

最后cookie結果:

 

目前嘗試了mechanize、urllib、selenium、headless chrome、requests、htmlunit、phantomjs、scrapy

目前已經嘗試了以上八種,個人覺得還是selenium獲取cookie比較全,信息比較完整,獲取cookie的字段也是比較穩定的,經過這兩天的研究cookie,就是selenium獲取cookie的速度比較慢,看看還有沒啥辦法優化速度,繼續查閱別的方式來獲取cookie。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM