Python 3.4带有cookie的HTTP POST请求

时间:2015-01-30 06:43:51

标签: python cookies

我在构建一个方法时遇到问题,该方法将使用标题和数据(用户名和密码)执行HTTP POST请求,并将检索生成的Cookie。

这是我迄今为止的最新尝试:

def do_login(username, password):
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
               "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
    cj = http.cookiejar.CookieJar()
    req = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    data = {"Username": username, "Password": password}
    req.open("http://example.com/login.php", data)

但是每当我尝试更改方法时,我都会遇到异常。此外,响应cookie是否会存储在CookieJar cj中,还是仅用于发送请求Cookie?

1 个答案:

答案 0 :(得分:1)

经过一些研究后,似乎数据不能直接作为req.open的参数传递,而是需要将其转换为URL编码的字符串。这是解决方案对我有用:

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}

cj = http.cookiejar.CookieJar()
req = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
req.addheaders = list(headers.items())

# The data should be URL-encoded and then encoded using UTF-8 for best compatilibity
data = urllib.parse.urlencode({"Username": username, "Password": password}).encode("UTF-8")
res = req.open("http://example.com/login.php", data)