python http.request autentification cookie web login



我有这个小功能:

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到第二个请求..如何做到这一点?

编辑为 使用 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

另类

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

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

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

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

最新更新