實現流程
- 使用
cookielib.LWPCookieJar 持久化 Cookie。
- 構建登錄 POST 請求(email、password、domain、origURL)。
- 驗證登錄成功(檢查重定向 URL)。
- 保存 Cookie 供下次復用。
- 解析好友動態頁面(正則提取
<article> 內容)。
核心代碼
import urllib2, urllib, cookielib, re
class Renren:
def __init__(self):
self.cj = cookielib.LWPCookieJar()
try: self.cj.load('./renren.cookie')
except: pass
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
urllib2.install_opener(self.opener)
def login(self, email, pwd):
data = urllib.urlencode({
'email': email, 'password': pwd,
'domain': 'www.renren.com',
'origURL': 'https://www.renren.com/home'
})
req = urllib2.Request('https://www.renren.com/PLogin.do', data)
resp = self.opener.open(req)
if 'home' in resp.geturl():
print("Login OK")
self.cj.save('./renren.cookie')
self._parse_feed(resp.read())
else:
print("Login Failed")
def _parse_feed(self, html):
# 簡易正則提取文章
articles = re.findall(r'(.*?)', html, re.S)
for art in articles:
user = re.search(r']*>(.+?)
', art)
text = re.search(r'(.+?)\s', art)
if user and text:
print(f"{user.group(1)}: {text.group(1)}")
print("-" * 40)
if __name__ == '__main__':
r = Renren()
r.login('your_email', 'your_password')
注意事項
- 人人網已停止服務,代碼僅供學習 HTTP 協議、Cookie 管理、正則解析參考。
- 現代網站多採用動態渲染/Token 驗證,需使用 Selenium/Playwright 或分析 API 接口。
- 爬蟲請遵守
robots.txt、控制頻率、合法合規。