有些网站登录需要输入图片验证码,图片验证码是个随机值,要抓取正确的图片选择创建会话session将登录时需要提交的表单和图片信息抓取,再利用图片验证工具将下载的图片自动读取,从而实现自动验证码登录。
#图片验证码验证登录,首先进去登录的界面,将验证码图片下载下来,因为验证码是会随时变化的,随着cookies信息变化而变化,每次提交表单信息的时候需要注意表单里面的信息是否改变,
# 表单里的信息可以在源网页代码中找到,将变化的表单值填入新的表单数据中,优于验证码每次访问页面都会改变,所以应该将保留验证码关键信息保存,
# 创建会话session,每次访问页面时都是同一个信息头,验证码也可以保存下来。
import requests
from bs4 import BeautifulSoup
import pytesseract
from PIL import Image
from PIL import ImageEnhance
#创建一个会话
s = requests.Session()
def login(headers,__VIEWSTATE):
image = Image.open('code3.png')
img = image.convert('RGB')
enhancer = ImageEnhance.Color(img)
enhancer = enhancer.enhance(0)
enhancer = ImageEnhance.Brightness(enhancer)
enhancer = enhancer.enhance(2)
enhancer = ImageEnhance.Contrast(enhancer)
enhancer = enhancer.enhance(8)
enhancer = ImageEnhance.Sharpness(enhancer)
img = enhancer.enhance(20)
img = img.convert('L')
threshold = 140
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
out = img.point(table, '1')
out.show()
img = img.convert('RGB')
img1 = pytesseract.image_to_string(img)
print(img1)
code = img1
post_url = 'https://so.gushiwen.org/user/login.aspx?from=http%3a%2f%2fso.gushiwen.org%2fuser%2fc#输入链接
form_data = {
'__VIEWSTATE':__VIEWSTATE,
'__VIEWSTATEGENERATOR':'C93BE1AE',
'from': 'http://so.gushiwen.org/user/collect.aspx',
'email': '账号',
'pwd':'密码',
'code': code,
'denglu': '登录', }
response2 = s.post(url=post_url,headers=headers,data = form_data)
with open(r'login.html','w',encoding='utf8')as fp:
fp.write(response2.text)
def download_image(post_url,headers):
html = s.get(url=post_url, headers=headers).text
print(type(html))
soup = BeautifulSoup(html, 'lxml')
image_src = 'https://so.gushiwen.org/RandCode.ashx' + soup.find('img', id='imgCode')['src']
__VIEWSTATE = soup.find('input',id='__VIEWSTATE')['value']
response1 = s.get(image_src)
with open('code3.png', 'wb')as fp:
fp.write(response1.content)
return __VIEWSTATE
def main():
post_url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36'
}
__VIEWSTATE = download_image(post_url,headers)#下载图片验证码到本地的文件夹中
login(headers,__VIEWSTATE)
if __name__ == '__main__':
main()