模拟登录12306
编码流程
12306:https://kyfw.12306.cn/otn/resources/login.html
- 使用selenium打开登录界面
- 对验证码图片进行截图
注:直接请求验证码图片可能导致请求到的验证码与登录界面验证码不一样。所有采用截图 - 使用超级鹰进行验证码识别
如果不清楚基本基本操作,可以到这里
具体操作过程写在注释中
代码实现
from selenium import webdriver
from lxml import etree
from ChaoJiYin import Chaojiying_Client
from selenium.webdriver import ActionChains
from time import sleep
# 1. 准备好验证码识别函数
def getCodeText(imgPath, codeType):
chaojiying = Chaojiying_Client('1257965244', '123456', '919873') # 用户中心>>软件ID 生成一个替换 96001
im = open(imgPath, 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
print(chaojiying.PostPic(im, codeType))
return chaojiying.PostPic(im, codeType)
# 2. 实例化一个浏览器对象
bro=webdriver.Chrome(executable_path=r'C:\Users\Lenovo\PycharmProjects\pythonProject1\venv\爬虫之selenium\chromedriver.exe')
# 3. 打开浏览器,将页面最大化(方便截图)
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
bro.maximize_window()
# 4. 转到账号登录界面
# 4.1 定位到“账号登录”
btn_login=bro.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a')
# 4.2 点击
btn_login.click()
# 5. 输入账号密码
# 5.1 定位到账号密码
user_name=bro.find_element_by_xpath('//*[@id="J-userName"]')
password=bro.find_element_by_xpath('//*[@id="J-password"]')
# 5.2 输入账号,密码
user_name.send_keys('123412')
password.send_keys('y1234132')
# 6.识别验证码
# 6.1 定位到验证码图片,进行元素截图
login_img=bro.find_element_by_xpath('//*[@id="J-loginImg"]')
login_img.screenshot('./code.png') # 截图
# 6.2 打码平台识别验证码
# 该验证码类型为9004
img_str=getCodeText('./code.png',9004)['pic_str']
# 注意:返回值需要的是坐标值,可能有多个,所有要进行处理
xy_list=[] #存储坐标
# 6.3 处理返回值,如果是多个,由'|'隔开
if '|' in img_str:
code_list=img_str.split('|')
#6.4 将x , y 分开,重新组合到一个列表中
for code in code_list:
xy_list_1=[]
x=code.split(',')[0]
y=code.split(',')[-1]
xy_list_1.append(x)
xy_list_1.append(y)
#6.5 组合好的一组(x,y)加入到xy_list中
xy_list.append(xy_list_1)
#6.7 如果只有一组坐标,将这一组加入
else:
xy_list_1 = []
x = code_list.split(',')[0]
y = code_list.split(',')[-1]
xy_list_1.append(x)
xy_list_1.append(y)
xy_list.append(xy_list_1)
# 7 进行验证码的点击
for i in xy_list:
# 实例化动作链
action=ActionChains(bro)
# 点击指定元素中的指定坐标位置
# 因为取出来的是字符,所有要转换为数字
# 第一个参数为定位到的验证码图片元素,第二个参数为x,最后一个为y
action.move_to_element_with_offset(login_img,float(i[0]),float(i[-1])).click().perform()
# 8. 登录
login_btn=bro.find_element_by_xpath('//*[@id="J-login"]')
login_btn.click()
# 休息一秒,防止滑块验证码还没刷新出来
sleep(1)
# 9. 拖动滑块验证码
# 定位滑块
slide=bro.find_element_by_xpath('//*[@id="nc_1_n1z"]')
# 拖动滑块
action_slide=ActionChains(bro)
action_slide.click_and_hold(slide)
# 向左拖动300像素
action_slide.move_by_offset(300,0).perform()
# 关闭
sleep(2)
bro.quit()