python实现人人网的自动登录

python实现人人网的自动登录

学习了一个多星期的python,写一个自动登录人人网的脚本练习一下,我使用的版本为Python 3.2.2。

上网搜了下,有许多示例,不过基本上都是Python 2.x写的,琢磨了好久终于登录成功了,代码如下:
import urllib.request
import urllib.parse
import http.cookiejar

class 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 = "[email protected]", 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)



你可能感兴趣的:(python,url,domain,email,import,login)