Python 程序貌似没问题 ,登录豆瓣为啥失败呢?

2018-07-31 10:41:47 +08:00
 istill
程序运行后,打印页面,页面仍然是未登录状态。但没发现哪里有问题啊,求高手指点。(由于隐私,这里的用户名和密码是随便写的,但测试的时候用的真实有效的账户密码)
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO

url1 = "https://accounts.douban.com/login"
url2 = "https://www.douban.com/contacts/list"
username = "123456789@@@.com"
passsword = "123456789"

header = {
"Referer":"https://www.douban.com/login",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
}

response = requests.get(url1)
response2 = response.text #获取网页登录页面的 HTML 代码
# print(response2)

def captcha(): #查找登录页面是否需要验证码
if "captcha_image" in response2:
soup1 = BeautifulSoup(response2, 'html.parser')
soup2 = soup1.find_all(attrs={"name": "captcha-id"})
soup2 = str(soup2)
soup3 = BeautifulSoup(soup2, 'html.parser') #获取验证码 ID
global captchaid
captchaid = soup3.input["value"]
# print(captchaid)
yzm_url1 = soup1.find_all(attrs={"id": "captcha_image"})
yzm_url1 = str(yzm_url1)
yzm_url2 = BeautifulSoup(yzm_url1,'html.parser')
yzm_url3 = yzm_url2.img["src"] #获取验证码的 URL
yzm_response = requests.get(yzm_url3)
image = Image.open(BytesIO(yzm_response.content))
image.show()
yzm_shuru = input("输入验证码:")
global captcha_solution
captcha_solution = yzm_shuru
global postData_has_captcha
postData_has_captcha = { # 有验证码的 post 数据
"source": "None",
"redir": "https://www.douban.com",
"form_email": username,
"form_password": passsword,
"captcha-solution": captcha_solution,
"captcha-id": captchaid,
"login": "登录"
}
return "有验证码"
else:
return "无验证码"

panduan_yzm = captcha()

postData_no_captcha ={ #无验证码的 post 数据
"source":"None",
"redir":"https://www.douban.com",
"form_email":username,
"form_password":passsword,
"login":"登录"
}

def denglu_has_captcha(): #有验证码的登录函数
global s
s = requests.session()
f = s.post(url1,header,postData_has_captcha)

def denglu_no_captcha(): #无验证码的登录函数
global s
s = requests.session()
f = s.post(url1,header,postData_no_captcha)

if panduan_yzm == "有验证码": #开始登陆
denglu_has_captcha()
print("有验证码,已登录")
r = s.get(url2)
print(r.text)
elif panduan_yzm == "无验证码":
denglu_no_captcha()
print("无验证码,已登录")
r = s.get(url2)
print(r.text)
else:
pass
1304 次点击
所在节点    Python
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/475577

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX