Python使用selenium实现网页用户名 密码 验证码自动登录功能

yipeiwu_com5年前Python基础

好久没有学python了,反正各种理由吧(懒惰总会有千千万万的理由),最近网上学习了一下selenium,实现了一个简单的自动登录网页,具体如下。

1.安装selenium:

如果你已经安装好anaconda3,直接在windows的dos窗口输入命令安装selenium:

python -m pip install --upgrade pip

查看版本pip show selenium

2.接着去http://chromedriver.storage.googleapis.com/index.html下载chromedriver.exe(根据chrome的版本下载对应的)

3.将下载好的chromedriver.exe解压后放到指定目录

4.安装tesseract-ocr.exe 配置环境变量

5.安装pytesseract : pip install pytesseract

6.python脚本

思路:6.1登录页面按F12检查元素,获取用户名 密码 验证码 验证码图片的元素id

   6.2.调用chromedriver

   6.3.截取验证码图片的位置

   6.4.pytesseract识别图片中字符,最后验证码识别为空!!???这个待解决

   6.5.脚本如下:

from selenium import webdriver
from PIL import Image
import pytesseract
import os,time
chromedriver = "D:\Program Files\Anaconda3\selenium\webdriver\chromedriver.exe" #这里写本地的chromedriver 的所在路径
os.environ["webdriver.Chrome.driver"] = chromedriver #调用chrome浏览器
driver = webdriver.Chrome(chromedriver)
driver.get("http://xxxx.com") #该处为具体网址
driver.refresh() #刷新页面
driver.maximize_window() #浏览器最大化
#获取全屏图片,并截取验证码图片的位置
driver.get_screenshot_as_file('a.png')
location = driver.find_element_by_id('imgValidateCode').location
size = driver.find_element_by_id('imgValidateCode').size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
a = Image.open("a.png")
im = a.crop((left,top,right,bottom))
im.save('a.png')
time.sleep(1)
#打开保存的验证码图片
image = Image.open("a.png")
#图片转换成字符
vcode = pytesseract.image_to_string(image)
print(vcode)
#填充用户名 密码 验证码
driver.find_element_by_id("staffCode").send_keys("username")
driver.find_element_by_id("pwd").send_keys("password")
driver.find_element_by_id("validateCode").send_keys(vcode)
#点击登录 
driver.find_element_by_id("loginBtn").click()

总结

以上所述是小编给大家介绍的Python实现网页用户名 密码 验证码自动登录功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python 3.8中实现functools.cached_property功能

前言 缓存属性( cached_property )是一个非常常用的功能,很多知名Python项目都自己实现过它。我举几个例子: bottle.cached_property Bottl...

修改默认的pip版本为对应python2.7的方法

现在系统中同时有python2.7和python3.5 终端输入python跳出来的也是python2.7的信息 但是输入pip -V跳出来的却是对应于pip3.5的 那么解决办法就是...

Python导入txt数据到mysql的方法

本文实例讲述了Python导入txt数据到mysql的方法。分享给大家供大家参考。具体分析如下: 从TXT文本转换数据到MYSQL数据库,接触一段时间python了 第一次写东西 用的是...

python 表格打印代码实例解析

编写一个名为printTable()的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样: t...

使用python读取.text文件特定行的数据方法

使用python读取.text文件特定行的数据方法

如何用python循环读取下面.txt文件中,用红括号标出来的数据呢? 首先,观察数据可知,不同行的第一个数据元素不一样,所以考虑直接用正则表达式。 再加上,对读和写文件的操作,就行了...