PHP Curl代码转换为Python的urlfetch - 需要帮助
这是我的PHP代码,使用了Curl。我需要在GAE Python中用urlfetch实现相同的功能。请问我该如何将这些参数传递给urlfetch呢?请帮帮我。
$curl = curl_init();
$timeout = 30;
// Logining to my TNT
curl_setopt ($curl, CURLOPT_URL, "https://my.tnt.com/myTNT/login/LoginInitial.do?cmd=1&navigation=1");
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, "userid=aaaa@bb.com&password=1234qwe");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($curl, CURLOPT_COOKIESESSION, 1);
curl_setopt ($curl, CURLOPT_COOKIEFILE, "userid=; password=; JSESSIONID=E1FC9A6D18002370BD4AF7DDBBA617A0; BIGipServermy_tnt_com_pool=2636720036.20480.0000");
curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl, CURLOPT_MAXREDIRS, 20);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:5.0.1) Gecko/20100101 Firefox/5.0.1");
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($curl, CURLOPT_REFERER, "https://my.tnt.com/myTNT/login/LoginInitial.do");
$text = curl_exec($curl);
$pos = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
这是我的Python代码。
from google.appengine.api import urlfetch
import urllib
class MainHandler(webapp.RequestHandler):
def get(self):
url = "https://my.tnt.com/myTNT/login/LoginInitial.do?cmd=1&navigation=1"
form_fields = {
"userid": "aaaa@bb.com",
"password": "1234qwe",
}
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url=url,
payload=form_data,
method=urlfetch.POST,
validate_certificate='TRUE',
headers={'Host': 'my.tnt.com',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive': '115',
'Connection': 'keep-alive',
'Referer': 'https://my.tnt.com/myTNT/login/LoginInitial.do',
'Cookie': 'userid=; password=; JSESSIONID=E1FC9A6D18002370BD4AF7DDBBA617A0; BIGipServermy_tnt_com_pool=2636720036.20480.0000',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': '45',
}
)
self.response.out.write(result.final_url)
我正在尝试访问MyTNT网页。所以我首先需要登录这个页面。上面的代码是用来登录mytnt网站的。当我运行PHP代码时,它会重定向到mytnt的主页(https://my.tnt.com/myTNT/landing/landingPage.do)。但是当我运行Python文件时,它却重定向回了同一个登录页面。使用urlfetch执行Python文件时,登录没有成功。
1 个回答
0
我猜你的PHP代码可能在用一种叫“cookie jar”的东西,这种东西在mechanize这个库里可以找到。
我之前用过mechanize来简单地抓取网站上的信息,但没有用它来登录,所以我不能百分之百确定它能否帮到你,不过我觉得这是你最好的选择。