我正在尝试使用 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
这不会返回第一项:
关于python - Selenium API 在我的 Python 程序中找不到所需的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692085/