Python 获取 Cookie 的方法
在 Python 中,获取网站的 Cookie 有多种方法,下面将列举几种不同的实现方法,并进行详细解释。
1. 使用 requests 库发送请求获取 Cookie
import requests
response = requests.get('http://example.com')
cookie = response.cookies.get_dict()
print(cookie)
使用 requests 库发送 GET 请求,并通过 `response.cookies.get_dict()` 方法获取到返回的 Cookie,并以字典形式进行打印。
2. 使用 urllib 库发送请求获取 Cookie
import urllib.request
response = urllib.request.urlopen('http://example.com')
cookie = response.getheader('Set-Cookie')
print(cookie)
使用 urllib 库发送 GET 请求,并通过 `response.getheader('Set-Cookie')` 获取到返回的 Cookie,并进行打印。
3. 使用 selenium 库模拟浏览器发送请求获取 Cookie
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://example.com')
cookie = driver.get_cookies()
print(cookie)
使用 selenium 库创建一个 Chrome 浏览器实例,并访问网站后,通过 `driver.get_cookies()` 获取到网站返回的 Cookie,并进行打印。
4. 使用 http.cookiejar 库发送请求获取 Cookie
import urllib.request
import http.cookiejarcookie_jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))
response = opener.open('http://example.com')cookie_dict = {}
for cookie in cookie_jar:
cookie_dict[cookie.name] = cookie.valueprint(cookie_dict)
使用 http.cookiejar 库创建一个 CookieJar 实例,并使用 urllib.request 库的 build_opener 方法创建一个带有 Cookie 处理器的 opener 对象。然后通过 opener 发送请求,获取到返回的 Cookie,并以字典形式进行打印。
这些方法各有优劣,具体使用哪种方法取决于你的需求和代码环境。其中,使用 requests 库是最常用和简便的方式。
希望以上内容能帮助到你,如果还有其他问题,请随时提问。