国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python cookielib 登錄人人網的實現代碼

2020-02-23 04:50:44
字體:
來源:轉載
供稿:網友

先上腳本吧,等下來講下知識點:
代碼如下:
#!/usr/bin/env python
#encoding=utf-8
import sys
import re
import urllib2
import urllib
import cookielib

class Renren(object):

def __init__(self):
self.name = self.pwd = self.content = self.domain = self.origURL = ''
self.operate = ''#登錄進去的操作對象
self.cj = cookielib.LWPCookieJar()
try:
self.cj.revert('renren.coockie')
except Exception,e:
print e

self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
urllib2.install_opener(self.opener)


def setinfo(self,username,password,domain,origURL):
'''設置用戶登錄信息'''
self.name = username
self.pwd = password
self.domain = domain
self.origURL = origURL

def login(self):
'''登錄人人網'''
params = {'domain':self.domain,'origURL':self.origURL,'email':self.name, 'password':self.pwd}
print 'login.......'
req = urllib2.Request(
'http://www.renren.com/PLogin.do',
urllib.urlencode(params)
)

self.operate = self.opener.open(req)

if self.operate.geturl() == 'http://www.renren.com/Home.do':
print 'Logged on successfully!'
self.cj.save('renren.coockie')
self.__viewnewinfo()
else:
print 'Logged on error'

def __viewnewinfo(self):
'''查看好友的更新狀態'''
self.__caiinfo()


def __caiinfo(self):
'''采集信息'''

h3patten = re.compile('<h3>(.*?)</h3>')#匹配范圍
apatten = re.compile('<a.+>(.+)</a>:')#匹配作者
cpatten = re.compile('</a>(.+)/s')#匹配內容
infocontent = self.operate.readlines()
# print infocontent
print 'friend newinfo:'
for i in infocontent:
content = h3patten.findall(i)
if len(content) != 0:
for m in content:
username = apatten.findall(m)
info = cpatten.findall(m)
if len(username) !=0:
print username[0],'說:',info[0]
print '----------------------------------------------'
else:
continue

ren = Renren()
username = ''#你的人人網的帳號
password = ''#你的人人網的密碼
domain = 'renren.com'#人人網的地址
origURL = 'http://www.renren.com/Home.do'#人人網登錄以后的地址
ren.setinfo(username,password,domain,origURL)
ren.login()

主要用到了python cookielib,urllib2,urllib這3個模塊,這3個模塊是python做http這方面比較好的模塊.


self.cj = cookielib.LWPCookieJar()

try:
self.cj.revert('renren.coockie')
except Exception,e:
print e
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))

urllib2.install_opener(self.opener)
這幾行是在本地建立人人網的cookies,因為人人網要驗證cookies才能登錄,你運行這個腳本的話,會發現在當前目錄 有個程序會自動建立一個renren.cookie這個文件。

我這里renren.cookie的信息是: #LWP-Cookies-2.0 Set-Cookie3: WebOnLineNotice_244225225=1; path="/"; domain=".renren.com"; path_spec; domain_dot; expires="2010-04-11 06:59:33Z"; version=0 總結一下如果網站登錄要用cookie的話,就要用到cookielib這個模塊,不然你用程序登錄不了網站,過斷時間在寫個urlib的例子,大家可以先用上面這個腳本玩玩!體會下python 人人網代碼的樂趣!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新余市| 和硕县| 封丘县| 元氏县| 常德市| 太仆寺旗| 特克斯县| 昭通市| 东丰县| 永德县| 上蔡县| 东乌珠穆沁旗| 奇台县| 盐边县| 五寨县| 孟州市| 建始县| 清水县| 比如县| 磴口县| 抚宁县| 望谟县| 娄底市| 章丘市| 广昌县| 肥西县| 永胜县| 泰顺县| 太白县| 保靖县| 谢通门县| 电白县| 格尔木市| 新安县| 临沧市| 广汉市| 普宁市| 花莲市| 读书| 常德市| 邯郸市|