Cookielib 是你的朋友。但是您需要从浏览器获取更多信息,而不仅仅是 cookie 名称和值:
cookies = {"username": "USERNAME", "session": "xxxxxxx"...}
如果您提供这些值,您应该能够在您的请求中重新创建会话:
cookies = [{
"name": "username",
"value": "USERNAME",
"domain": "domain",
"path": "path",
"secure": "secure",
}]
使用以下命令重新创建会话:
import cookielib
import urllib2
cj = cookielib.CookieJar()
for cookie in cookies:
c = cookielib.Cookie(version=1,
name=cookie["name"],
value=cookie["value"],
port=None,
port_specified=False,
domain=cookie["domain"],
domain_specified=False,
domain_initial_dot=False,
path=cookie["path"],
path_specified=True,
secure=cookie["secure"],
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False)
cj.set_cookie(c)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.open(urllib2.Request('http://www.example.com')
未经测试的代码。