0
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()

How do i implement the cookielib to create a session and please explain line by line Thank you

4

2 回答 2

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()来生成请求。

于 2013-08-08T03:43:12.340 回答
0

你会想要使用一个OpenerDirector。从文档中

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()
于 2013-08-08T03:43:32.573 回答