简体   繁体   中英

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

I'm trying to use Selenium to automatically download songs from a website, but something is going wrong when I try to find the desired element. I used method find_elements_by_xpath() . Go to http://moresound.tk/music/# to visit the website. The error is TimeoutException , but my web browser has already shown the element I want. Can you tell me what's wrong?

    # 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()

The error is:

  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: 

错误截图 .

网站页面截图 .

Your XPath is also selecting a hidden <li> which will fail the clickable check:

在此处输入图片说明

Instead, select only the actual search result <li> items in a more specific wrapper:

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

Which does not return that first item:

在此处输入图片说明

Sometimes, Firefox doesnt interact with Elements which are not actually visible.

Make sure if you are checking with the latest Firefox version and its corresponding driver.

If that doesnt work, try checking the same code with Chrome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM