我需要的是从第一个网站中提取 uid cookie 并用它打开第二个(这是一种授权)
它既不适用于此代码:
#!/usr/bin/env python
import urllib, urllib2, cookielib
import socket, Cookie
def extract(url):
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
opener.addheaders = [('User-agent',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20110201 Firefox/2.0.0.14')]
response = opener.open(url)
for cookie in jar:
precious_value = cookie.value
return precious_value
site1 = "mysite1.com"
site2 = "mysite2.com"
cp = urllib2.HTTPCookieProcessor()
cj = cp.cookiejar
cj.set_cookie(cookielib.Cookie(0, cookie_name,
extract(site1),
'80', False, 'domain', True, False, '/path',
True, False, None, False, None, None, None))
opener = urllib2.build_opener(urllib2.HTTPHandler(),cp)
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)'))
print opener.open(site2).read()
也不是这样:
#!/usr/bin/env python
import urllib, urllib2, cookielib
def extract(url):
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
opener.addheaders = [('User-agent',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20110201 Firefox/2.0.0.14')]
response = opener.open(url)
for cookie in jar:
precious_value = cookie
return precious_value
site1 = "mysite1.com"
site1 = "mysite2.com"
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1;
en-GB; rv:1.8.1.14) Gecko/20110201 Firefox/2.0.0.14')]
opener.addheaders = [('Cookies', extract(site1))]
response = opener.open(site2)
print response.read()
但是我已经通过“请求”库在这里成功了,代码看起来不错:
cookies= dict(mycid='9ti6cACUi6AqxXBG2H9AMPkrfRbBJPalKTAh_bLcuQ8c8C')
r = requests.get(url, cookies = cookies)
print r.text
这对我来说很好,我对请求没有任何反对......但在两次第一次尝试中我仍然做错了什么?在这两种情况下,提取过程都可以正常工作,并且我看到 uid 已正确提取。我想问题出在 add_headers 区域。答案很明显,但仍然可以通过。有人可以帮忙吗?
1) 仅使用 urllib 或 urllib2 将 cookie 传递到标头的正确方法是什么?
2)如何将它作为可以更改的参数传递,而不仅仅是引用提取的对象?
3)我应该如何正确地将它作为对象名称/值传递?
提前致谢