这不是马上就要放假了嘛,闲来无事的爬虫小白(也就是我)写一个12306购票的脚本吧,用到selemium,还挺简单的,再次强调,本人是小白哦,大佬不要喷我,多的不说了直接奉上代码
from time import sleep
from selenium.webdriver import ChromeOptions
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
user_name = input('请输入账号:')
password = input('请输入密码:')
start_time = input('开始时间(2022-05-30):')
departure = input('请输入出发地:')
destination = input('请输入目的地:')
#selenium规避检测
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')
#屏蔽密码保存框
option.add_experimental_option("prefs",{"credentials_enable_service":False,"profile.password_manager_enabled":False})
#模拟登录
driver = webdriver.Chrome(executable_path='D:\脚本\chromedriver.exe',options=option)
driver.get('https://kyfw.12306.cn/otn/resources/login.html')
user_name_1 = driver.find_element(By.XPATH,'//*[@id="J-userName"]').send_keys(user_name)
password_1 = driver.find_element(By.XPATH,'//*[@id="J-password"]').send_keys(password)
btn = driver.find_element(By.XPATH,'//*[@id="J-login"]').click()
sleep(1)
#滑动验证码
validation = driver.find_element(By.XPATH,'//*[@id="nc_1_n1z"]')
action = ActionChains(driver)
action.click_and_hold(validation)
action.move_by_offset(400,0)
action.release()
action.perform()
sleep(2)
print('登录成功')
#购票
driver.get('https://kyfw.12306.cn/otn/leftTicket/init')
driver.find_element(By.XPATH,'//*[@id="qd_closeDefaultWarningWindowDialog_id"]').click()
#出发地
driver.find_element(By.XPATH,'//*[@id="fromStationText"]').click()
driver.find_element(By.XPATH,'//*[@id="fromStationText"]').send_keys(departure)
driver.find_element(By.XPATH,'//*[@id="citem_1"]').click()
#目的地
driver.find_element(By.XPATH,'//*[@id="toStationText"]').click()
driver.find_element(By.XPATH,'//*[@id="toStationText"]').send_keys(destination)
driver.find_element(By.XPATH,'//*[@id="citem_0"]').click()
#出发日
driver.find_element(By.XPATH,'//*[@id="train_date"]').clear()
driver.find_element(By.XPATH,'//*[@id="train_date"]').send_keys(start_time)
#查询
driver.find_element(By.XPATH,'//*[@id="query_ticket"]').click()
sleep(1)
#点击预定
driver.find_element(By.XPATH,'//*[@id="ticket_4p000G696505_03_05"]/td[13]/a').click()
sleep(1)
#选择乘坐人
driver.find_element(By.XPATH,'//*[@id="normal_passenger_id"]/li[1]/label').click()
#确认
driver.find_element(By.XPATH,'//*[@id="submitOrder_id"]').click()
sleep(3)
#选座
driver.find_element(By.XPATH,'//*[@id="erdeng1"]/ul[2]/li[1]').click()
#确认
driver.find_element(By.XPATH,'//*[@id="qr_submit_id"]').click()
print('看什么看,赶紧去打钱!')