I'm making a python music player, which plays music through the headless chrome browser using Youtube Music. However, when I fill in the input form for the song name, I would sometimes get a noSuchElementException. It happens less often than not, and when it doesn't happen the code runs smoothly without any problems.
Here is my the section of my code:
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("- - - - - - -")
And here is the exception:
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)
Help would be much appreciated. Thanks in advance