python實現人人網的自動登入
學習了一個多星期的python,寫一個自動登入人人網的指令碼練習一下,我使用的版本為Python 3.2.2。
上網搜了下,有許多樣本,不過基本上都是Python 2.x寫的,琢磨了好久終於登入成功了,代碼如下:
import urllib.requestimport urllib.parseimport http.cookiejarclass LoginRenren(): def __init__(self): """log in www.renren.com""" #self.origURL = "http://www.renren.com/home" #self.domain = "renren.com" self.log_url = "http://www.renren.com/PLogin.do" self.cj = http.cookiejar.CookieJar() self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj)) urllib.request.install_opener(self.opener) #Installing an opener is only necessary if you want urlopen to use that opener def login(self, email, password): self.email = email self.password = password params = {"email":self.email, "password":self.password}#, "origURL":self.origURL, "domain":self.domain} params = urllib.parse.urlencode(params) params = params.encode('utf-8') #response = self.opener.open(self.log_url,params) response = urllib.request.urlopen(self.log_url, params) file = open("d:\\renren.html", "wb") file.write(response.read())def login(email = "myemail@163.com", password = "mypassword" ): renren = LoginRenren() renren.login(email, password)
一些解釋
1.查看到登入介面的源碼,擷取表單內容,經過測試發現,只有email、password兩項是必需的。
2.提交表單,有兩個可選的函數
self.opener.open(self.log_url,params)
urllib.request.urlopen(self.log_url, params)
兩個函數均返回一個http.client.HTTPResponse對象
注意,使用這種方法時,前面必需調用函數urllib.request.install_opener(self.opener)