Python模拟登录实战(二)
目标:1、模拟登录豆瓣,2、自动更改签名和发表说说。
代码如下:
1 #!/usr/bin/env python2 # -*- 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)
以上是 Python模拟登录实战(二) 的全部内容, 来源链接: utcz.com/z/387772.html