赞
踩
源码:
- from selenium import webdriver
- from selenium.webdriver.common.by import By # driver.find_element(By.ID,'query_ticket')
- from selenium.webdriver.support.wait import WebDriverWait # 显示等待
- from selenium.webdriver import ActionChains # 动作链
- from selenium.webdriver import ChromeOptions # 规避检测
- import time
-
-
- # def login():
- # """
- # 判断网页url是否改变:
- # 当验证登录成功后,网页url会改变,即表示登录成功!
- # :return:
- # """
- # while True:
- # if driver.current_url != url:
- # print("用户登录成功!")
- # break
-
- def login():
- driver.find_element(By.ID, 'J-userName').send_keys('输入12306账号')
- driver.find_element(By.ID, 'J-password').send_keys('输入12306密码')
-
- driver.find_element(By.ID, 'J-login').click()
- time.sleep(2)
- # 滑动模块
- clock = driver.find_element(By.CLASS_NAME, 'nc_iconfont')
-
- action = ActionChains(driver)
- # 点击长按滑动模块
- action.click_and_hold(clock).perform()
- # for i in range(5):
- action.move_by_offset(300, 0)
- time.sleep(0.1)
- action.release().perform()
-
-
- def buy():
- """
- :return:
- """
- login()
- # 将 出发地 目的地 出发日期 -- 添加到cookie
- driver.add_cookie({'name': '_jc_save_fromDate', 'value': '2022-04-01'})
- driver.add_cookie({'name': '_jc_save_fromStation', 'value': '%u5E7F%u5DDE%u4E1C%2CGGQ'})
- driver.add_cookie({'name': '_jc_save_toStation', 'value': '%u6F6E%u9633%2CCNQ'})
-
- # 显示等待
- # 定位链接文字点击确定
- WebDriverWait(driver, 30).until(lambda x: x.find_element_by_link_text("确定")).click()
- WebDriverWait(driver, 30).until(lambda x: x.find_element_by_link_text("车票")).click()
- WebDriverWait(driver, 30).until(lambda x: x.find_element_by_link_text("单程")).click()
-
- # 点击查询
- driver.find_element(By.ID, 'query_ticket').click()
-
- # 获取当前页面(判断)
- url = driver.current_url
- while True:
- # 抢票
- if url != driver.current_url:
- print('查询成功!')
- break
- else:
- try:
- for i in driver.find_elements(By.CLASS_NAME, "btn72"): # 注:elements
- i.click()
- except:
- print("正在查询...") # 无预票避免错误跳出
-
- # 选择乘车人
- print('请选择乘车人')
- driver.find_element(By.ID, "normalPassenger_0").click()
- # 提交订单
- driver.find_element(By.LINK_TEXT, "提交订单").click()
- print('订单提交...')
-
- time.sleep(3)
- driver.find_element(By.LINK_TEXT, "确认").click()
- print('下单成功!待支付...')
-
-
- if __name__ == '__main__':
- # 启动浏览器
- url = "https://kyfw.12306.cn/otn/resources/login.html"
- # 设置浏览器,防止selenium被检测出来
- options = ChromeOptions()
- options.add_argument("--disable-blink-features=AutomationControlled")
- options.add_experimental_option('excludeSwitches', ['enable-automation'])
-
- driver = webdriver.Chrome(options=options)
- driver.get(url)
- buy()
模拟滑动验证码:
- # 滑动模块
- clock = driver.find_element(By.CLASS_NAME, 'nc_iconfont')
-
- action = ActionChains(driver)
- # 点击长按滑动模块
- action.click_and_hold(clock).perform()
- # for i in range(5):
- action.move_by_offset(300, 0)
- time.sleep(0.1)
- action.release().perform()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。