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

标签 python selenium

我正在尝试使用 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: 

Error screenshot

Website page screenshot .

最佳答案

您的 XPath 还选择了隐藏的 <li>这将导致可点击检查失败:

enter image description here

相反,仅选择实际搜索结果 <li>更具体的包装中的项目:

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

这不会返回第一项:

enter image description here

关于python - Selenium API 在我的 Python 程序中找不到所需的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692085/

相关文章:

java - 如何让 Selenium webdriver 等待元素将其属性更改为 Java 中的其他内容

python - 在 selenium 网络驱动程序中如何选择正确的 iframe

python - 使用 Selenium 和 Beautifulsoup 解析 Airdna map 悬停在文本上

python - 将字符串(数字)增加到总计并打印

python - 在 RasPi 上使用 psutil(Python 模块)时出现问题

PHP 和 python 节俭

selenium - 在selenium中打开chrome devtool检查器检查器

python - Firefox 工作但 PhantomJS 抛出无法使用 css 选择器找到元素

python - 惯用的 Python : 'times' loop

python - 如何从 Pandas 数据框中删除方括号