selenium登录古诗文网

from lxml import etree
import sys
from PIL import Image

sys.path.append("public")
from chaojiying import codeResult
# selenium主要是为了解决requests无法执行JavaScript代码的问题;
from selenium import webdriver  # 用来驱动浏览器的
from time import sleep

browser = webdriver.Chrome()
browser.get(
    "https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx"
)
sleep(6)
img = browser.get_screenshot_as_png()
with open("dist/古诗文网登录/screen.png", 'ab+') as f:
    f.write(img)
code_img_ele = browser.find_elements_by_id("imgCode")[0]
location = code_img_ele.location  # 验证码图片左上角的坐标 x,y
print('location:', location)
size = code_img_ele.size  #验证码标签对应的长和宽
print('size:', size)
#左上角和右下角坐标
rangle = (int(location['x']), int(location['y']),
          int(location['x'] + size['width']),
          int(location['y'] + size['height']))
#至此验证码图片区域就确定下来了

i = Image.open('dist/古诗文网登录/screen.png')
code_img_name = 'dist/古诗文网登录/code.png'
#crop根据指定区域进行图片裁剪
frame = i.crop(rangle)
frame.save(code_img_name)

#将验证码图片提交给超级鹰进行识别

browser.find_elements_by_id("email")[0].send_keys("古诗文账号")
sleep(2)
browser.find_elements_by_id("pwd")[0].send_keys("古诗文密码")
sleep(2)

# 截图验证码

# 并识别验证码
code = codeResult(code_img_name)['pic_str']
print(code)
# 然后填入验证码
browser.find_elements_by_id("code")[0].send_keys(code)
# 提交
browser.find_elements_by_id("denglu")[0].click()

browser.quit()

 实现思路:

  1.使用webdriver请求要登录的页面;

  2.对当前页面进行截图,并存储到本地;

  3.找到验证码,并通过定位,计算出左上角和右下角的数值;

  4.并对保存到本地的图片,根据定位的四个值进行截图,截图后保存到本地;

  5.通过超级鹰中的接口识别出图片的验证码,并把验证码,手机号,密码,输入到输入框中

  6.点击确认按钮,就可以登录

posted @ 2021-11-10 16:26  墨染清浅  阅读(80)  评论(0编辑  收藏  举报