使用Python的urlopen函数设置cookie可以通过以下步骤实现:
from urllib import request
url = "http://example.com"
,req = request.Request(url)
cookie_jar = request.CookieJar()
cookie_handler = request.HTTPCookieProcessor(cookie_jar)
opener = request.build_opener(cookie_handler)
response = opener.open(req)
cookies = cookie_jar._cookies
完整的代码示例如下:
from urllib import request
url = "http://example.com"
req = request.Request(url)
cookie_jar = request.CookieJar()
cookie_handler = request.HTTPCookieProcessor(cookie_jar)
opener = request.build_opener(cookie_handler)
response = opener.open(req)
cookies = cookie_jar._cookies
这样,通过urlopen函数设置了cookie后,可以在后续的请求中使用相同的opener对象,保持cookie的状态。
领取专属 10元无门槛券
手把手带您无忧上云