简体   繁体   English

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

[英]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. 我正在尝试使用Selenium从网站上自动下载歌曲,但是当我尝试找到所需的元素时出现了问题。 I used method find_elements_by_xpath() . 我使用了find_elements_by_xpath()方法。 Go to http://moresound.tk/music/# to visit the website. 转到http://moresound.tk/music/#访问该网站。 The error is TimeoutException , but my web browser has already shown the element I want. 错误是TimeoutException ,但是我的网络浏览器已经显示了我想要的元素。 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: 您的XPath还选择了一个隐藏的<li> ,它将使可点击检查失败:

在此处输入图片说明

Instead, select only the actual search result <li> items in a more specific wrapper: 而是在更具体的包装器中仅选择实际搜索结果<li>项目:

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

Which does not return that first item: 哪个不返回第一个项目:

在此处输入图片说明

Sometimes, Firefox doesnt interact with Elements which are not actually visible. 有时,Firefox不会与实际上不可见的Elements进行交互。

Make sure if you are checking with the latest Firefox version and its corresponding driver. 确保您正在检查最新的Firefox版本及其对应的驱动程序。

If that doesnt work, try checking the same code with Chrome. 如果这样不起作用,请尝试使用Chrome检查相同的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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