精易论坛

标题: Python自学记录--api识别,模拟登陆 [打印本页]

作者: 菠萝儿    时间: 2021-10-5 16:14
标题: Python自学记录--api识别,模拟登陆
之前看教程学习用超级鹰,根据论坛师兄们指点尝试用百度的智能识别,可以实现,但是成功率不高
零基础小白自学中,求指点!

目标网站:https://www.gushiwen.cn/
  1. #baidu-aip 智能识别验证码

  2. from aip import AipOcr
  3. import requests
  4. from lxml import etree
  5. import time

  6. """ 你的 APPID AK SK """
  7. APP_ID = 'APP_ID'
  8. API_KEY = 'API_KEY'
  9. SECRET_KEY = 'SECRET_KEY'

  10. #识别验证码图片
  11. def tranformImgCode(imgPath):
  12.     client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
  13.     im = open(imgPath, 'rb').read()
  14.     return client.basicGeneral(im)["words_result"][0]["words"] #取验证码

  15. t = int(round(time.time() * 1000)) #时间戳

  16. session = requests.Session() #维持会话,可以让我们在跨请求时保存某些参数

  17. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}

  18. #获取验证码图片
  19. url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx' #登陆地址

  20. page_text = session.get(url=url,headers=headers).text #获取登陆地址内容

  21. #解析验证码图片地址
  22. tree = etree.HTML(page_text)
  23. img_src = 'https://so.gushiwen.cn'+tree.xpath('//img[@id="imgCode"]/@src')[0]+'?t='+str(t)

  24. VIEWSTATE = tree.xpath('//*[@id="__VIEWSTATE"]/@value')
  25. VIEWSTATEGENERATOR = tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value') #动态数据

  26. #将验证码保存到本地
  27. img_data= session.get(img_src,headers=headers).content

  28. with open(r'D:\代码保存\a.jpg','wb') as fp:
  29.     fp.write(img_data)

  30. #识别验证码
  31. code_text = tranformImgCode(r'D:\代码保存\a.jpg')
  32. print(code_text)

  33. login_url = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'

  34. data = {
  35.     '__VIEWSTATE': VIEWSTATE,
  36.     '__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR,  
  37.     'from': 'http://so.gushiwen.cn/user/collect.aspx',
  38.     'email': '网页账号',
  39.     'pwd': '网页密码',
  40.     'code': code_text,
  41.     'denglu': '登录',
  42. }

  43. #点击登陆按钮发起请求,获取了登陆成功后对应的页码源码数据
  44. page_text_login = session.post(url=login_url,headers=headers,data=data).text

  45. #保存网页
  46. with open(r'D:\代码保存\gushiwen.html','w',encoding='utf-8') as fp:
  47.     fp.write(page_text_login)

复制代码






欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4