import urllib2
import urllib
url = "http://www.torn.com/authenticate.php"
username = raw_input("Your username; ")
password = raw_input("Your password: ")
query = {'player':username, 'password':password}
data_query = urllib.urlencode(query)
sending_data = urllib2.Request(url, data_query)
print sending_data()
response = urllib2.urlopen(sending_data)
print "You are currently logged unto to:", response.geturl()
print response.read()
如何实现cookielib来创建会话,请逐行解释谢谢
答案 0 :(得分:0)
from cookielib import CookieJar
cj = CookieJar()
login_data = urllib.urlencode({'j_username' : username, 'j_password' : password})
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.open("http://www.torn.com/authenticate.php", login_data)
首先,您要初始化CookieJar。然后编码您的凭据,因为它们需要以某种形式发送以供PHP服务器读取。然后你必须初始化一个开启者,它基本上是一个HTTP客户端,并配置它来使用你的CookieJar。然后将您的登录信息提交给服务器以创建会话并生成cookie。要继续使用这些Cookie,请使用opener.open()
代替urllib2.urlopen
(尽管您仍然可以使用urllib2.Request()
生成请求。
答案 1 :(得分:0)
您需要使用OpenerDirector
。
来自the documentation:
import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
因此,为了传递数据,您的代码应如下所示:
import urllib2
import urllib
import cookielib
url = "http://www.torn.com/authenticate.php"
username = raw_input("Your username; ")
password = raw_input("Your password: ")
query = {'player':username, 'password':password}
data_query = urllib.urlencode(query)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
response = opener.open(url, data_query)
print "You are currently logged unto to:", response.geturl()
print response.read()