0

I am currently using python 3.6.5, selenium version 3.14.0

If I created a web element like the following:

driver.execute_script("""var body = document.getElementsByTagName('body').item(0);var div = document.createElement('div');div.setAttribute('id', 'ZZZ');body.appendChild(div);""")

I wasn't able to use something like the following:

    wait.until(
        expected_conditions.presence_of_element_located(
            (By.ID, 'ZZZ')
        )
    )

I have double checked that the element is successfully created but using the APIs provided by the selenium package (e.g. find_element_by_id, and scripts like above) I wasn't able to locate the element.

Question: Is there something else I need to do after injecting new elements after execute_script? or currently, it is not possible?

I can get the element via the following though:

new_element = driver.execute_script('return document.getElementById("ZZZ");')

But this will be difficult for me if I couldn't use the default APIs provided by the selenium package (e.g. find_element_by_id)

forestclown
  • 1,582
  • 4
  • 25
  • 39

2 Answers2

3

Below code works for me:

driver.get('http://www.google.com')
elem = driver.find_element_by_name("q")
driver.execute_script("var body = document.getElementsByTagName('body').item(0);var div = document.createElement('div');div.setAttribute('id', 'ZZZ');body.appendChild(div);")

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "ZZZ"))
)
driver.quit()
Kireeti Annamaraj
  • 1,037
  • 1
  • 8
  • 12
1

Once the WebElement is successfully created and further if you want to validate the presence of the added element within the DOM Tree you can print() the outerHTML of the element using the following solution:

  • Code Block:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('http://www.google.com')
    elem = driver.find_element_by_name("q")
    driver.execute_script("var body = document.getElementsByTagName('body').item(0);var div = document.createElement('div');div.setAttribute('id', 'ZZZ');body.appendChild(div);")
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ZZZ")))
    print(element.get_attribute("outerHTML"))
    driver.quit()
    
  • Console Output:

    <div id="ZZZ"></div>
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352