Selenium Driver: How to find the element added after the webpage is loaded?

Ken T :

So the webpage has a button that after clicking will add an element to the webpage, in which I can't find using selenium

Some imaginary code as follows to explain the problem I experience:

from selenium import webdriver
d = webdriver.Chrome()
#Go to my target website
d.get("https://some_website_url") #ref1
#Okay now loading of the website is done. `d` will not be updated and this is the problem!!

#Click my target button and an element with id="SecretButton" is loaded.
d.find_element_by_css_selector("#secretlyupdatethewebpage").click()

#Find #SecretButton but to no avail. 
#It can be found in the html panel of Chrome Developer Tools
#but cannot be found in the webdriver `d`, as `d` won't be 
#updated after #ref1
d.find_element_by_css_selector("#SecretButton").click()

How can I find that #SecretButton?

DebanjanB :

To find and invoke click() on the secret button you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using ID:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "SecretButton"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#SecretButton"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='SecretButton']"))).click()
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18493&siteId=1