目標:一、模擬登陸豆瓣,二、自動更改簽名和發表說說。html
代碼以下:python
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 __author__ = 'ziv·chan' 4 5 6 import re 7 import time 8 import requests 9 from PIL import Image 10 11 url = 'https://www.douban.com/' 12 13 headers = { 14 'origin' : 'https://www.douban.com', 15 'referer' : 'https://www.douban.com/', 16 'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36' 17 } 18 19 session = requests.session() 20 21 # 獲取驗證碼Id 22 def get_captchaId(): 23 html = session.get(url,headers=headers) 24 html.encoding = 'utf-8' 25 pageCode = html.text 26 pattern = re.compile('captcha[?]id=(.*?)&',re.S) 27 captchaId = re.findall(pattern,pageCode)[0] 28 return captchaId 29 30 # 獲取驗證碼圖片 31 def get_captchaSolu(captchaId): 32 url_plus = 'https://www.douban.com/misc/captcha?id=%s&size=s' % captchaId 33 cha = session.get(url_plus,headers=headers) 34 with open('cap_douban.png','wb') as f: 35 f.write(cha.content) 36 f.close() 37 im = Image.open('cap_douban.png') 38 im.show() 39 im.close() 40 captcha = raw_input('請輸入驗證碼') 41 return captcha 42 43 # 編輯簽名 44 def edit_signature(ck): 45 url = 'https://www.douban.com/j/people/143780683/edit_signature' 46 data = { 47 'ck' : ck, 48 'signature' : '人間有味是清歡。' 49 } 50 headers = { 51 'origin' : 'https://www.douban.com', 52 'referer' : 'https://www.douban.com/people/143780683/', 53 'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 54 'x-requested-with' : 'XMLHttpRequest' 55 } 56 session.post(url,data=data,headers=headers) 57 58 # 編輯說說 59 def edit_words(ck): 60 url = 'https://www.douban.com/' 61 data = { 62 'ck' : ck, 63 'comment' : '天之涯,地之角,知交半零落。一斛濁酒盡餘歡,今宵別夢寒。' 64 } 65 headers = { 66 'origin': 'https://www.douban.com', 67 'referer': 'https://www.douban.com/', 68 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36' 69 } 70 session.post(url,data=data,headers=headers) 71 72 # 獲取ck 73 def get_ck(): 74 url = 'https://www.douban.com/people/143780683/' 75 html = session.get(url,headers=headers) 76 pageCode = html.text 77 # print pageCode 78 pattern = re.compile('ck=(.*?)[(">)]',re.S) 79 ck = re.findall(pattern,pageCode)[0] 80 return ck 81 82 if __name__ == '__main__': 83 captchaId = get_captchaId() 84 captcha = get_captchaSolu(captchaId) 85 form_data = { 86 'source' : 'index_nav', 87 'form_email' : '18362972928', 88 'form_password' : 'ChelseaFC.2', 89 'captcha-solution' : captcha, 90 'captcha-id' : captchaId 91 } 92 session.post('https://www.douban.com/accounts/login',data=form_data,headers=headers) 93 94 ck = get_ck() 95 edit_signature(ck) 96 # 避免衝突,設置延時 97 time.sleep(5) 98 edit_words(ck)