22

我正在尝试打开以下网站并检索初始 cookie 并将其用于第二个 url-open 但如果您运行以下代码,它会输出 2 个不同的 cookie。如何将初始 cookie 用于第二个 url-open?

import cookielib, urllib2

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

home = opener.open('https://www.idcourts.us/repository/start.do')
print cj

search = opener.open('https://www.idcourts.us/repository/partySearch.do')
print cj

如您所见,每次输出显示 2 个不同的 cookie:

<cookielib.CookieJar[<Cookie JSESSIONID=0DEEE8331DE7D0DFDC22E860E065085F for www.idcourts.us/repository>]>
<cookielib.CookieJar[<Cookie JSESSIONID=E01C2BE8323632A32DA467F8A9B22A51 for www.idcourts.us/repository>]>
4

3 回答 3

21

这不是 urllib 的问题。该网站做了一些时髦的东西。您需要为其请求几个样式表来验证您的会话 ID:

import cookielib, urllib2

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# default User-Agent ('Python-urllib/2.6') will *not* work
opener.addheaders = [
    ('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11'),
    ]


stylesheets = [
    'https://www.idcourts.us/repository/css/id_style.css',
    'https://www.idcourts.us/repository/css/id_print.css',
]

home = opener.open('https://www.idcourts.us/repository/start.do')
print cj
sessid = cj._cookies['www.idcourts.us']['/repository']['JSESSIONID'].value
# Note the +=
opener.addheaders += [
    ('Referer', 'https://www.idcourts.us/repository/start.do'),
    ]
for st in stylesheets:
    # da trick
    opener.open(st+';jsessionid='+sessid)
search = opener.open('https://www.idcourts.us/repository/partySearch.do')
print cj
# perhaps need to keep updating the referer...
于 2011-01-04T00:48:27.200 回答
7

不是一个实际的答案(但评论太长了);可能对其他试图回答这个问题的人有用。

尽管我尽了最大努力,但我无法弄清楚这一点。

在 Firebug 中查看,对于 Firefox,cookie 似乎保持不变(正常工作)。

我添加urllib2.HTTPSHandler(debuglevel=1)了调试 Python 发送的标头,它似乎确实重新发送了 cookie。

我还添加了所有 Firefox 请求标头,看看是否有帮助(没有帮助):

opener.addheaders = [
    ('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'),
    ..
]

我的测试代码:

import cookielib, urllib2

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPSHandler(debuglevel=1))
opener.addheaders = [
    ('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'),
    ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
    ('Accept-Language', 'en-gb,en;q=0.5'),
    ('Accept-Encoding', 'gzip,deflate'),
    ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
    ('Keep-Alive', '115'),
    ('Connection', 'keep-alive'),
    ('Cache-Control', 'max-age=0'),
    ('Referer', 'https://www.idcourts.us/repository/partySearch.do'),
]

home = opener.open('https://www.idcourts.us/repository/start.do')
print cj

search = opener.open('https://www.idcourts.us/repository/partySearch.do')
print cj

我觉得我错过了一些明显的东西。

于 2011-01-03T09:37:42.610 回答
0

我认为,这是服务器的问题,它为每个请求设置一个新的 cookie。

于 2011-01-03T09:04:28.347 回答