0

I am trying to edit chrome browsers search and homepage using selenium/python. After navigating to chrome://settings/searchEngines and targeting the 'add' button with the ID 'addSearchEngine', I get an error when I run a .click function. How do I target this element correctly, or is there another way to update chromes search/startpage with python?

I'm guessing this element is trapped inside an iframe but I'm unable to find one on the page using the dev tools, xpath noted the following about the absolute xpath: "It might be a child of iframe from different src & it is not supported currently."

from selenium import webdriver

driver = webdriver.Chrome()
driver.set_page_load_timeout(10)
driver.get("chrome://settings/searchEngines")
driver.find_element_by_id("addSearchEngine").click()

Traceback (most recent call last):
  File "C:/Users/Jonathan/PycharmProjects/test_project/test_project/Main.py", line 20, in <module>
    driver.find_element_by_id("addSearchEngine").click()
  File "C:\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python37-32\lib\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":"css selector","selector":"[id="addSearchEngine"]"}
  (Session info: chrome=75.0.3770.142)
John James
  • 23
  • 4

2 Answers2

0

chrome://settings/searchEngines has Shadow DOM elements . You will need to use the driver.execute_script() to get handle of the shadowRoot element and ultimately get to the 'addSearchEngine' element.

Example python : shadowRoot python

Example Java : For chrome://downloads/ shadowRoot java

Rahul L
  • 4,249
  • 15
  • 18
0

Refer to this post for detailed explanation.

In your case you can do the below.

url = "chrome://settings/searchEngines"
driver.get(url)
addButton = driver.execute_script("return document.querySelector('settings-ui')"
                              ".shadowRoot.querySelector('#main')"
                              ".shadowRoot.querySelector('settings-basic-page.showing-subpage')"
                              ".shadowRoot.querySelector('settings-search-page')"
                              ".shadowRoot.querySelector('settings-search-engines-page')"
                              ".shadowRoot.querySelector('#addSearchEngine')")
addButton.click()

Screenshot:

enter image description here

supputuri
  • 13,644
  • 2
  • 21
  • 39