python http.request身份验证cookie web登录

时间:2014-12-19 11:44:12

标签: python http cookies request

我有这个小功能:

def wp_login_check(url,username,password):
    UA = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"
    headers = { 'User-Agent': UA, 'Content-type': 'application/x-www-form-urlencoded', 'Cookie': 'wordpress_test_cookie=WP+Cookie+check' }
    http = httplib2.Http(timeout=10, disable_ssl_certificate_validation=True)
    http.follow_redirects = True
    body = { 'log':username,'pwd':password,'wp-submit':'Login','testcookie':'1' }

    response, content = http.request(url, 'POST', headers=headers, body=urllib.urlencode(body))


    url2 = url.replace('/wp-login.php','/wp-admin/plugin-install.php')
    response1, content1 = http.request(url2)
    print content1

我需要使用第一个请求的cookie来第二次请求..怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

已编辑使用httplib2

从响应标头Set-cookie中抓取Cookie并将其包含在后续请求中:

def wp_login_check(url,username,password):
    UA = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"
    headers = { 'User-Agent': UA, 'Content-type': 'application/x-www-form-urlencoded', 'Cookie': 'wordpress_test_cookie=WP+Cookie+check' }
    http = httplib2.Http(timeout=10, disable_ssl_certificate_validation=True)
    http.follow_redirects = True
    body = { 'log':username,'pwd':password,'wp-submit':'Login','testcookie':'1' }

    response, content = http.request(url, 'POST', headers=headers, body=urllib.urlencode(body))

    # Grab the cookie for later presentation
    headers = {'Cookie': response['set-cookie']}

    url2 = url.replace('/wp-login.php','/wp-admin/plugin-install.php')
    response1, content1 = http.request(url2, headers=headers)
    print content1

<强>替代

如果可以,请使用requests模块会话而不是httplib2

import requests

s = requests.Session()
resp1 = s.post(url, headers=headers, data=body)
resp2 = s.post(...)

您会发现cookie将在会话中保留,然后在后续请求时显示给服务器。

您还会发现requests是一个更加愉快的模块。