2014-12-19 93 views
0

我有這個小funnction:蟒蛇http.request autentification 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)) 


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

我需要使用的第一個請求的cookie來第二次請求..怎麼能這樣?

回答

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模塊裂變,而不是:

import requests 

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

你會發現,cookie將在會議上堅持,然後提交給後續請求的服務器。

您還會發現requests是一個更好用的模塊。

+0

不,不可能,需要使用http.request – kingcope 2014-12-19 11:59:07

+0

@kingcope:無賴。 – mhawke 2014-12-19 12:00:47

+0

@kingcope:httplib2的回答 – mhawke 2014-12-19 12:27:26