Issue
When I go to https://www.youtube.com with Selenium and try to select the search bar using find_element_by_id() and using "masthead-search-term" as the ID, I get an error like this:
Traceback (most recent call last):
File "C:\Users\lauri\Desktop\Projects\Python Projects\test.py", line 9, in <module>
driver.find_element_by_id("masthead-search-term")
File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 341, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 843, in find_element
'value': value})['value']
File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
self.error_handler.check_response(response)
File "D:\Python\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"masthead-search-term"}
Why is that? Here's the code:
import selenium.webdriver as webdriver
driver = webdriver.Chrome(executable_path="D:\Applications\chromedriver")
driver.get("https://www.youtube.com")
driver.find_element_by_id("masthead-search-term")
Solution
You have to take care of a couple of things as follows:
While working with the Chrome browser, try to open in maximized mode, with disabling infobars and extensions which enables you to use the maximum available
Viewport
.Once you access the URL https://www.youtube.com, either wait for the loader to disappear or wait for the search box to be clickable.
Ensure the locators you are using are unique and correct. With Dev Tools of the Firefox Quantum 57.0b3 (64-bit) browser, the XPath expression of the search box seems to be
//input[@id='search']
.Here is the working code block with browser:
import selenium.webdriver as webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By options = Options() options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get("https://www.youtube.com") search_box = WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, "//input[@id='search']")) ) driver.find_element_by_xpath("//input[@id='search']").send_keys("Selenium")
Answered By - undetected Selenium
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.