Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

python - Unable to find_element_by_id when element is created via execute_script

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...