简体   繁体   中英

Python+Selenium reconstruct true HTML after executing javascript on page

I have this super simple code running in selenium

<input name="X" id="unique" value="" type="text">

<script>
    document.getElementById("unique").value="123";
</script>

I am able to get input value 123 by calling driver.execute_script('return document.getElementById("unique").value')

but I am not able to get real HTML code with updated value "123" using any of these methods

  1. driver.page_source - no updated value
  2. driver.execute_script("return document.documentElement.outerHTML") no updated value
  3. driver.execute_script("return document.getElementById("unique").outerHTML") no updated value either

is there any solution to this problem?

Why don't you just try using regular Selenium find_element to get the attribute? The point of using Selenium is so that you can access their built-in functionality to do this for you. Javascript is just meant to be a workaround for unique issues.

This will fetch the value attribute on the input element you posted:

input_value = driver.find_element_by_xpath("//input[@id='unique']").get_attribute("value")

This is functionally the same as driver.execute_script('return document.getElementById("unique").value')

Try it like this:

document.getElementById("unique").setAttribute('value', '123');

This way will definitely update the DOM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM