今天小编给大家分享一下获取cookie的方式有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
这里采用python2.7
第一种:mechanize
首先我们要使用mechanize,第一步:
pip install mechanize
第二步编写获取cookie代码:
import osimport mechanizeimport 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'].cookiejarfor 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 urllib2import cookielibfrom http import cookiejarfrom 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)
运行结果:
以上就是“获取cookie的方式有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网行业资讯频道。