简体   繁体   English

如何使用Mechanize接受和发送Cookie?

[英]How can I accept and send cookies with Mechanize?

I have a bash script, that logs in with a cookie and saves a text file from a URL. 我有一个bash脚本,该脚本使用cookie登录并从URL保存一个文本文件。 I need to achieve the same thing in Python with Mechanize, but I can't get it working. 我需要使用Mechanize在Python中实现相同的功能,但无法使其正常工作。 It's only two lines of bash and it's driving me mad. 仅有两行打击,这让我发疯。 I've looked at the Mechanize docs, but can't find out how to do it. 我看过Mechanize文档,但找不到如何做。

#!/bin/sh
base_url=https://myapp.url.com
sign_on_request="aK8Rj_mrVk3J-PDf9x6...LONG KEY...4ZPMd0w"
# Login
wget -q --keep-session-cookies --save-cookies savedcookie.txt --post-data="sign_on_request=$sign_on_request" -O - $base_url/login > /dev/null 2>&1
# Save CSV
wget -q --load-cookies savedcookie.txt -O output.txt $base_url/data

Here's what I tried: 这是我尝试过的:

import mechanize
import cookielib

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Login
req = mechanize.Request("https://myapp.url.com/login", "sign_on_request=aK8Rj_mrVk3J-PDf9x6...LONG KEY...4ZPMd0w")
cj.add_cookie_header(req)
res = mechanize.urlopen(req)

# Download
f = br.retrieve('https://myapp.url.com/data')[0]
print f

Have you tried res = br.open("https://myapp.url.com/login", data=...) instead of mechanize.Request ? 您是否尝试过使用res = br.open("https://myapp.url.com/login", data=...)代替mechanize.Request吗? Seems you would need to use the browser you created to do the login if you expect it to be able to do the retrieval. 如果您希望它能够进行检索,则似乎需要使用创建的浏览器进行登录。

You can use br.set_cookie("cookiename=cookievalue; expire=Wednesday, 13-Feb-13 15:00:00 GMT") But this method works only after you had made a call to some website. 您可以使用br.set_cookie("cookiename=cookievalue; expire=Wednesday, 13-Feb-13 15:00:00 GMT")但是此方法仅在您致电某个网站后才有效。 Use the same object br to call the further pages so that this cookie is sent automatically in br.open() method. 使用相同的对象br调用其他页面,以便此cookie在br.open()方法中自动发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM