Python3 豆瓣登录并评论,保存登录状态

2017-12-30 12:19:20来源:oschina作者:阿豪boy人点击

分享

使用requests模块,保存登录信息并评论

注意:


1. 每部电影只能评论一次,多次会保错403


2. 登录和评论的headers不一样,不然会报错500

import requests
requests = requests.Session()def login(requests):
headers = {
"Host": "www.douban.com",
"Connection": "keep-alive",
"Origin": "https://www.douban.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36",
"Referer": "https://www.douban.com/",
}
# 获取验证码
img_url = 'https://www.douban.com/j/misc/captcha'
response = requests.get(img_url, headers=headers)
js = response.json()
# 验证码地址和token
captcha_url = "https:" + js['url']
captcha_token = js['token']
print(captcha_url, captcha_token)
# 保存验证码需要使用content获取二进制流,文件写入需要使用wb+模式
response = requests.get(captcha_url, headers=headers)
with open("cap_img.jpg", mode='wb+') as f:
f.write(response.content)
# 登录
data = {
"source": "index_nav",
"form_email": "uid",
"form_password": "pwd",
"captcha-solution": input("请输入验证码:/n"),
"captcha-id": captcha_token
}
url = 'https://www.douban.com/accounts/login'
response = requests.post(url, data=data, headers=headers)
# 判断是否登录成功
print("成功" if "阿豪" in response.text else "失败")# url = "https://www.douban.com/people/165985804/"
# 获取个人主页,查看是否登录成功
# print(
# requests.get(url, headers=headers).text
# )
# 评论的电影的id
movie_id = "20495023"
url = "https://movie.douban.com/j/subject/%s/interest" % movie_id
data = {
"ck": "u08z",
"interest": "collect",
"rating": 5,
"foldcollect": "F",
"tags": "动画 亲情 音乐 2017 皮克斯 梦想",
"comment": "寻梦环游记是今年最好看的电影",
}
headers = {
"Host": "movie.douban.com",
"Connection": "keep-alive",
"Origin": "https://movie.douban.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36",
"Referer": "https://movie.douban.com/subject/%s/?from=showing" % movie_id,
}
response = requests.post(url, data=data, headers=headers)
print(response.text, response.status_code)login(requests)

微信扫一扫

第七城市微信公众平台