#encoding=utf-8
import urllib2
import urllib
import cookielib
def renrenBrower(url,user,password):
#登陆页面,可以通过抓包工具分析获得,如fiddler,wireshark
login_page = "http://www.renren.com/PLogin.do"
try:
#获得一个cookieJar实例
cj = cookielib.CookieJar()
#cookieJar作为参数,获得一个opener的实例
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#伪装成一个正常的浏览器,避免有些web服务器拒绝访问。
opener.addheaders = [('User-agent','Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0')]
#生成Post数据,含有登陆用户名密码。
data = urllib.urlencode({"email":user,"password":password})
#以post的方法访问登陆页面,访问之后cookieJar会自定保存cookie
opener.open(login_page,data)
#以带cookie的方式访问页面
op=opener.open(url)
#读取页面源码
data= op.read()
return data
except Exception,e:
print "aaaa"
#访问某用户的个人主页,其实这已经实现了人人网的签到功能。http://blog.chinaunix.net/uid-25979788-id-3481639.html
print renrenBrower("http://www.renren.com/home","1574038203@qq.com","123456")
http://www.renren.com/PLogin.do
那么我们是怎么知道表单提交地址呢?
1:查看网站代码
2:查看表单
提前表单的需要的数据
如: <img src="http://img.blog.csdn.net/20150605221718031?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzQ0NTUzMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />form中间就是整个表单
import urllib
import urllib2
import cookielib
filename = 'cookie1.txt'
#声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件
cookie = cookielib.MozillaCookieJar(filename)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
opener.addheaders = [('User-agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')]
postdata = urllib.urlencode({
"username":"xxxxxxxx,
"password":"xxxxxxxx",
"lt":"LT-381024-pHXsjYjSgZ2aR9P4QrG9YQ6rneqlhg",
"execution" : "e20s1",
"_eventId" : "submit"
})
#登录的URL
loginUrl = 'https://passport.csdn.net/account/login
'
#模拟登录,并把cookie保存到变量
result = opener.open(loginUrl,postdata)
#保存cookie到cookie.txt中
cookie.save(ignore_discard=True, ignore_expires=True)
#利用cookie请求访问另一个网址
gradeUrl = 'http://write.blog.csdn.net/postlist
'
#请求访问查询网址
result = opener.open(gradeUrl)
print result.read()
原文:http://blog.csdn.net/u013445530/article/details/46382285