selenium知识点整理&汇总

Selenium学习006-查询12306列车

2018-07-26  本文已影响48人  残阳夕露

Selenium学习笔记目录

查询有票的列车,并输出列车车次

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
try:
    driver = webdriver.Chrome()
    driver.get('https://kyfw.12306.cn/otn/leftTicket/init')
    driver.implicitly_wait((10))

    # 出发地
    driver.find_element_by_id('fromStationText').click() # 点击操作用于清空默认置灰的文字
    driver.find_element_by_id('fromStationText').send_keys('南京南')
    driver.find_element_by_id('fromStationText').send_keys(Keys.ENTER)  # 模拟键盘enter

    # 目的地
    driver.find_element_by_id('toStationText').click()
    driver.find_element_by_id('toStationText').send_keys('杭州东')
    driver.find_element_by_id('toStationText').send_keys(Keys.ENTER)  # 模拟键盘enter

    # 选择时间段
    driver.find_element_by_id('cc_start_time').click()
    driver.find_element_by_xpath("//*[@id='cc_start_time']/option[@value='06001200']").click()

    # 选择日期-->自动查询出结果
    driver.find_element_by_xpath(("//*[@id='date_range']/ul/li[2]")).click()

    # # 收集数据--方法一(本人首次做出来时使用的方法)
    # with_ticket_trains = [] # 有票的车次
    # without_ticket_trains =[] # 无票的车次
    # all_trains_info = driver.find_elements_by_xpath("//*[@id='queryLeftTable']/tr/td[4]")
    # for one_train_info in all_trains_info:
    #     train_number = one_train_info.find_element_by_xpath("../td[1]//*[@class='number']").text.strip()  # 查找车次
    #     if one_train_info.text in ('--', '无'): # 判断是否有票
    #         without_ticket_trains.append(train_number)
    #     else:
    #         with_ticket_trains.append(train_number)
    # # 打印出有票的列车车次
    # if len(with_ticket_trains) == 0:
    #     print('您所选的区间及时间范围内所有列车均已无票')
    # else:
    #     print('以下列车还有票:')
    #     for i in with_ticket_trains:
    #         print(f'{i:>6}')

    # 收集数据--方法二(后期发现只有有票的才含有class属性,代码如下)
    all_trains_info = driver.find_elements_by_xpath("//*[@id='queryLeftTable']/tr/td[4][@class]/../td[1]//a")
    for one in all_trains_info:
        print(one.text)


finally:
    driver.quit()
上一篇下一篇

猜你喜欢

热点阅读