iT邦幫忙

0

selenium爬取下拉式選單報錯

Tian 2022-11-15 16:48:531489 瀏覽
  • 分享至 

  • xImage

大家好,我是Python新手,想請問一下使用selenium爬取https://irs.thsrc.com.tw/IMINT/
的日期跟時間一直報錯
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with visible text: 1400
想問一下可以從哪方面下手,GOOGLE好久試過好多寫法都抓不到
PS.我爬取https://www.thsrc.com.tw/
上面的時刻表與票價是成功的,用相同方式去抓取訂票的元素就失敗QQ

程式碼如下:

def order_high_speed_rail(start_use,arrival_use,data_use,time_use):
    PATH="D:/PYTHONE/new/chromedriver_win32/chromedriver.exe" 
    #chromedriver檔案存放位置
    
    options = webdriver.ChromeOptions() 
    options.add_experimental_option("excludeSwitches", ["enable-logging"])
    driver = webdriver.Chrome(options=options, executable_path=PATH)

    url = "https://irs.thsrc.com.tw/IMINT/"
    driver.get(url)
    driver.find_element(by=By.CLASS_NAME,value="policy-btn-accept").click()
    

    #買票邏輯只能單程只能買標準車廂只能買全票
    ticket_use = "單程"
    typesofCar_use = "標準車廂"
    time.sleep(2)
    #上車
    driver.find_element(by=By.XPATH,value='//*[@id="BookingS1Form"]/div[3]/div[1]/div/div[1]/div/select').click()  
    start_use_from = Select(driver.find_element(by=By.NAME,value='selectStartStation'))    
    start_use_from.select_by_visible_text(start_use)
    
    #下車
    driver.find_element(by=By.XPATH,value='//*[@id="BookingS1Form"]/div[3]/div[1]/div/div[2]/div/select').click()  
    arrival_use_from = Select(driver.find_element(by=By.NAME,value='selectDestinationStation'))    
    arrival_use_from.select_by_visible_text(arrival_use)
    
    #日期
    data_find = driver.execute_script(f"document.getElementById('toTimeInputField').value='{data_use}'") 
    time.sleep(2)
    
    #時間
    driver.find_element(by=By.XPATH,value='//*[@id="BookingS1Form"]/div[3]/div[2]/div/div[2]/div[1]/select')
    time_use_from = Select(driver.find_element(by=By.NAME,value='toTimeTable'))
    start_use_from.select_by_visible_text(time_use)
    time.sleep(5)

order_high_speed_rail("台中","彰化","2022.11.16","14:00")
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
johncoc
iT邦新手 3 級 ‧ 2022-11-15 18:08:04

問題應該是出在找不到name,options都沒有name的屬性

https://ithelp.ithome.com.tw/upload/images/20221115/20154377mOmDW8899I.jpg

Tian iT邦新手 5 級 ‧ 2022-11-15 18:34:14 檢舉

謝謝,但我還是想不到怎麼抓,只好走一個彎路了QAQ
附上程式碼,謝大哥講解XD

#時間
time_try = "23"
if int(time_try) > 2:
x = int(time_try) * 2 - 6
else:
x = int(time_try) +1
time_mix = f'//*[@id="BookingS1Form"]/div[3]/div[2]/div/div[2]/div[1]/select/option[{x}]'
driver.find_element(by=By.XPATH,value=time_mix).click()

我要發表回答

立即登入回答