其他分享
首页 > 其他分享> > selenium模拟登录12306网站(2021最新方法)实测可用

selenium模拟登录12306网站(2021最新方法)实测可用

作者:互联网

from selenium import webdriver
from time import sleep
from selenium.webdriver import ChromeOptions
from selenium.webdriver import ActionChains

url = 'https://kyfw.12306.cn/otn/resources/login.html'

#实例化一个浏览器对象,打开浏览器,同时进行检测规避
# 防止12306禁止selenium
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
# pro = Chrome(options=chrome_Options)
#实例化一个浏览器对象,打开浏览器
pro = webdriver.Chrome(executable_path='./chromedriver.exe',options=options)
pro.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})
# script = 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined,});'
# pro.execute_script(script)
#实例化一个浏览器对象,打开浏览器
# pro = webdriver.Chrome(executable_path='./chromedriver.exe',options=option)

#向浏览器发起指定url的请求
pro.maximize_window()  # 最大化浏览器
pro.get(url)

#点击使用账号密码登录
botton = pro.find_element_by_xpath('//*[@id="toolbar_Div"]/div[2]/div[2]/ul/li[2]/a')
botton.click()

#输入账号
id_inqut = pro.find_element_by_id('J-userName')
id_inqut.send_keys('userName')#个人账号替换userName

#输入密码
mm_inqut = pro.find_element_by_id('J-password')
mm_inqut.send_keys('Password')#个人密码替换Password

#点击登录
login_botton = pro.find_element_by_id('J-login')
login_botton.click()

#等两秒(可以不等)
sleep(2)

#动作链,移动滑块,完成验证
span = pro.find_element_by_xpath('//*[@id="nc_1_n1z"]')
action = ActionChains(pro)#实例化一个动作链
action.click_and_hold(span)#点击并长按鼠标
action.move_by_offset(350, 0).perform()#拖动鼠标向右平移350px
action.release()#松开鼠标

#如想保留登录状态,下面代码可以注释掉

#等两秒(可以不等)
sleep(2)
#关闭网页
pro.quit()

标签:webdriver,浏览器,pro,selenium,id,find,12306,2021,options
来源: https://blog.csdn.net/jdsydwr/article/details/120388204