Python enables automatic logon to Renren
After learning python for more than a week, write a script to automatically log on to Renren. My version is Python 3.2.2.
I searched through the Internet and found many examples, but basically all of them were written in Python 2.x. After a long time, I finally succeeded in logging on. The Code is as follows:
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)
Some explanations
1. Check the source code of the logon interface and obtain the form content. After testing, it is found that only email and password are required.
2. submit the form. There are two optional functions.
Self. opener. Open (self. log_url, Params)
Urllib. Request. urlopen (self. log_url, Params)
Both functions return an HTTP. Client. httpresponse object.
Note: before using this method, you must call the urllib. Request. install_opener (self. opener) function)