<p>生成cookie.txt的一个简单方法是这个chrome扩展:<a href="https://chrome.google.com/webstore/detail/cookietxt-export/lopabhfecdfhgogdbojmaicoicjekelh" rel="nofollow noreferrer">https://chrome.google.com/webstore/detail/cookietxt-export/lopabhfecdfhgogdbojmaicoicjekelh</a></p>
<pre><code>import urllib2, cookielib
url = 'https://example.com/path/default.aspx'
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
cj = cookielib.LWPCookieJar()
# cj.load signature: filename=None, ignore_discard=False, ignore_expires=False
cj.load('/path/to/my/cookies.txt')
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
req = urllib2.Request(url, None, txheaders)
handle = urllib2.urlopen(req)
</code></pre>
<p>[更新]</p>
<p>对不起,我粘贴的是一段被遗忘已久的旧代码片段。从LWPCookieJar文档字符串:</p>
<blockquote>
<p>The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-Cookie3" is the format used by the libwww-perl libary, not known to be compatible with any browser, but which is easy to read and doesn't lose information about RFC 2965 cookies.</p>
</blockquote>
<p>因此它与现代浏览器生成的cookie.txt不兼容。如果您尝试加载它,您将得到:<code>LoadError: 'cookies.txt' does not look like a Set-Cookie3 (LWP) format file</code>。</p>
<p>您可以作为OP执行以下操作并转换文件:</p>
<blockquote>
<p>there is something wrong with the format of the output from chrome extension. I just googled the lwp problem and found: code.activestate.com/recipes/302930-cookielib-example the code spits out the cookie in lwp format and then I follow your steps as it is. - <a href="https://stackoverflow.com/users/848746/james-w">James W</a></p>
</blockquote>
<p>您还可以使用这个<a href="https://addons.mozilla.org/en-US/firefox/addon/cookie-exporter/?src=api" rel="nofollow noreferrer">Firefox addon</a>,然后使用“工具->;导出cookies”。确保cookies.txt文件中的第一行是“#Netscape HTTP Cookie文件”,并使用:</p>
<pre><code>cj = cookielib.MozillaCookieJar('/path/to/my/cookies.txt')
cj.load()
</code></pre>