你了解cookie的获取方法吗?今天要给大家介绍的就是几种cookie的获取方法,下面就让我们一起详细的来了解一下吧!
cookie获取方式1:
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)
运行的结果:
cookie获取方式2:
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
运行的结果:
cookie获取方式3:
selenium
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)
运行的结果:
cookie获取方式4:
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("=========")
运行的结果:
以上的4种cookie获取方法你都了解了吗?当然方法远远不止这些,更多cookie获取方式,可以继续关注本站了解哦。