簡體   English   中英

Selenium API在我的Python程序中找不到所需的元素

[英]Selenium API can't find the desired element in my Python program

我正在嘗試使用Selenium從網站上自動下載歌曲,但是當我嘗試找到所需的元素時出現了問題。 我使用了find_elements_by_xpath()方法。 轉到http://moresound.tk/music/#訪問該網站。 錯誤是TimeoutException ,但是我的網絡瀏覽器已經顯示了我想要的元素。 你能告訴我怎么了嗎?

    # coding: utf-8
    from selenium import webdriver
    import re
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC

    profile = webdriver.FirefoxProfile()
    profile.set_preference('browser.download.dir','d://')
    profile.set_preference('browser.download.folderList',2)
    profile.set_preference('browser.download.manager.showWhenStarting',False)
    driver = webdriver.Firefox(executable_path='H:/fire_fox_driver/geckodriver')
    driver.get('http://moresound.tk/music/#')
    driver.find_element_by_xpath("//body").click()
    driver.find_element_by_id("search_input").send_keys(u'周傑倫')
    driver.find_element_by_id("search_btn").click()
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, 
    '//body/div[@id="main"]//li')))
    song = driver.find_element_by_xpath('//body/div[@id="main"]//li')
    song.click()

錯誤是:

  Traceback (most recent call last):File ...
     line 23, in <module>
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, '//body/div[@id="main"]//li')))
  File ...
 line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

錯誤截圖

網站頁面截圖

您的XPath還選擇了一個隱藏的<li> ,它將使可點擊檢查失敗:

在此處輸入圖片說明

而是在更具體的包裝器中僅選擇實際搜索結果<li>項目:

//div[@id="MS_search_result"]//li

哪個不返回第一個項目:

在此處輸入圖片說明

有時,Firefox不會與實際上不可見的Elements進行交互。

確保您正在檢查最新的Firefox版本及其對應的驅動程序。

如果這樣不起作用,請嘗試使用Chrome檢查相同的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM