python cookielibログイン人人網の実装コード

3649 ワード

まずシナリオを書きましょう.後で知識点を話します.
 
  
#!/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('

(.*?)

')#
apatten = re.compile('(.+):')#
cpatten = re.compile('(.+)\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,urllib 2,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を検証してからログインするので、このスクリプトを実行すると、現在のディレクトリに自動的にrenrenrenを作成するプログラムがあります.クッキーというファイル.
ここにいるよクッキーの情報は、#LWP-Cookies-2.0 Set-Cookie 3:WebOnLineNotice_244225225=1; path="/"; domain=".renren.com"; path_spec; domain_dot; expires="2010-04-11 06:59:33Z"; version=0まとめてみましょう.もしサイトにログインするにはクッキーを使うなら、クッキーlibというモジュールを使う必要があります.そうしないと、プログラムでサイトにログインできません.urlibの例を書くのに時間がかかります.皆さんはまず上のスクリプトで游ぶことができます.python人人網コードの楽しみを体得します!