Unable to find_element_by_id when element is created via execute_script

后端 未结 2 1251
说谎
说谎 2020-12-22 06:41

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 = docu         


        
相关标签:
2条回答
  • 2020-12-22 06:59

    @KireetiAnnamaraj answer was just perfect. Further if you want to validate that the presence of the added element within the HTML 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>
      
    0 讨论(0)
  • 2020-12-22 07:08

    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()
    
    0 讨论(0)
提交回复
热议问题