python爬虫之12306模拟登陆
登录流程:
1、登录界面输入账号密码,点击立即登录
2、弹出手机验证界面,输入身份证后4位,点击获取验证码等待验证码后手动输入,点击确定登录
实现代码如下:
#需求:登陆12306,输入短信验证码后登陆
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
#导入动作链对应的类
from selenium.webdriver import ActionChains
from selenium.webdriver.edge.options import Options
edge_options = Options()
edge_options.add_experimental_option("detach", True)
edge_options.add_argument("--guest") # 启用guest模式。
# edge_options.add_experimental_option("detach",True)
# 创建一个Edge WebDriver实例
bro = webdriver.Edge(options=edge_options)bro.get('https://kyfw.12306.cn/otn/resources/login.html')
handle = bro.current_window_handle # 获取当前窗口句柄username = bro.find_element(By.ID,'J-userName')
password = bro.find_element(By.ID,'J-password')username.send_keys('账号')
password.send_keys('密码')btn = bro.find_element(By.ID,'J-login')
btn.click()# card = bro.find_element(By.ID,'id_card')
# card.send_keys('6220')handles = bro.window_handles # 获取所有窗口句柄
for window_handle in handles: # 循环比较句柄if window_handle != handle: # 如果窗口句柄与当前窗口句柄不一致,则切换到该窗口bro.switch_to.window(window_handle)
sleep(3)
card = bro.find_element(By.ID,'id_card')
card.send_keys('XXXX')btn_vertify = bro.find_element(By.ID,'verification_code')
btn_vertify.click()# code = bro.find_element(By.ID,'code')
sleep(60)
# yanzhengma = input()
# sleep()
# code.send_keys('035145')btn_primary = bro.find_element(By.ID,'sureClick')
btn.click()sleep(3)
bro.quit()