验证码登录
import requests
# 古诗文网登录页面的URL地址
url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
}
# 获取网络源代码
response = requests.get(url=url, headers=headers)
content = response.text
# 使用BeautifulSoup来解析网页源码,获取__VIEWSTATE和__VIEWSTATEGENERATOR参数
from bs4 import BeautifulSoup
soup = BeautifulSoup(content, 'lxml')
# 获取__VIEWSTATE
VIEWSTATE = soup.select('#__VIEWSTATE')[0].attrs.get('value')
print('VIEWSTATE: ', VIEWSTATE)
# 获取__VIEWSTATEGENERATOR
VIEWSTATEGENERATOR = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')
print('VIEWSTATEGENERATOR: ', VIEWSTATEGENERATOR)
# 获取验证码图片
code = soup.select('#imgCode')[0].attrs.get('src')
code_url = 'https://so.gushiwen.cn' + code
# import urllib.request
# urllib.request.urlretrieve(url=code_url,filename='code.jpg')
session = requests.session()
# 验证码url的内容
response_code = session.get(code_url)
# webbrowser.open(code_url)
# 图片下载要使用二进制数据
content_code = response_code.content
# wb模式就是将二进制数据写入文件
with open('code.jpg', 'wb') as fp:
fp.write(content_code)
# 获取验证码图片后,下载到本地,观察本地验证码,在控制台输入code
code_name = input('请输入登录验证码:')
# 点击登录
url_post = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
data_post = {
'__VIEWSTATE': VIEWSTATE,
'__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR,
'from': 'http://so.gushiwen.cn/user/collect.aspx',
'email': '[email protected]',
'pwd': 'dhc123456',
'code': code_name,
'denglu': '登录'
}
# 获取网络源代码(这里能用requests对象,要用验证码的session对象,保持一个Cookie环境)
response_post = session.post(url=url_post, headers=headers, data=data_post)
content_post = response_post.text
with open('denglu.html','w',encoding='utf-8') as pf:
pf.write(content_post)
标签:code,python,验证码,url,VIEWSTATEGENERATOR,requests,post,VIEWSTATE
From: https://www.cnblogs.com/dhcc/p/18303290