我正在制作一个python音乐播放器,该播放器使用Youtube Music通过无头的chrome浏览器播放音乐。但是,当我填写歌曲名称的输入表单时,有时会出现noSuchElementException。它发生的频率通常不那么高,并且如果不发生,则代码可以顺利运行而没有任何问题。
这是我的代码部分:
def searchMusic():
ask = input("What song would you like to listen to?: ")
print("- - - - - - - - ")
if ask != " ":
driver.implicitly_wait(10)
search_initiate = driver.find_element_by_xpath('//*[@id="icon"]')
search_initiate.click()
search_bar = WebDriverWait(driver,10).until(IF.presence_of_element_located((By.XPATH,
'/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-nav-bar/div[2]/ytmusic-search-box/div/div[1]/input')))
driver.implicitly_wait(10)
search_bar.send_keys(ask)
search_bar.send_keys(Keys.ENTER)
heading1 = driver.find_elements_by_xpath('//*[@id="contents"]/ytmusic-responsive-list-item-renderer')
for i in range(4):
print(heading1[i].text)
print("- - - - - - -")
这是个例外:
File "/Users/kevinhadinata/Desktop/Python/headless.py", line 92, in <module>
searchMusic()
File "/Users/kevinhadinata/Desktop/Python/headless.py", line 56, in searchMusic
search_initiate = driver.find_element_by_xpath('//*[@id="icon"]')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="icon"]"}
(Session info: headless chrome=85.0.4183.102)
我们将不胜感激。预先感谢
答案 0 :(得分:0)
只需检查元素是否存在:
check = driver.find_elements_by_xpath('//*[@id="icon"]')
if len(check) > 0:
go further
else:
no data
答案 1 :(得分:0)
Please use proper method to wait element so you can ignore nosuchelement issue,If you write and keep wait method in your program you can use that method anywhere and anytime in your programme
------------------------------------------------------
private static WebElement waitForElement(By locator, int timeout)
{
WebElement element=new WebDriverWait(driver,timeout).until(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
------------------------------------------------------
// for example if you want wait an element with id use below code
waitForElement(By.id(""),20);
20 is milliseconds