简体   繁体   中英

How to replace entire page after Javascript code done executing?

I am using a JS script to run some calculations on a page. I then use selenium to grab the text out of the results div.

results = json.loads(driver.find_element_by_id("results").text)

I would very much prefer to avoid using selenium and use requests instead:

results = json.loads(get(<url goes here>).text)

In order to accomplish this I would need to somehow replace the entire page (including JS) with the results in the form of a simple JSON string (no HTML tags). In other words:

<html>
    <head>
    ...
    </head>
    <body>
        <div id="results">{"blah":"1234", "test":"4567", ...}</div>
    ...
    <script>
    ...
    </script>
    </body>
</html>    

becomes a plain text string suitable for get(...).text

{"blah":"1234", "test":"4567", ...}

This string is modified by the JS code that runs after the page loads. Which means that the results would have to be stored and then used to create an entirely new page devoid of any HTML or JS. The original page replaces itself entirely.

An alternative would be to use JS to replace the entire <html>...</html> block and then erase itself.

Not sure this is possible.

Yes, I could probably use something like:

page = get(<url goes here>)
page.json()
...

I was hoping for an approach that removes everything from the page except the results.

Using python for the selenium part.

EDIT 1:

Here's code that shows how the page works.

https://jsfiddle.net/pkLu7uqz/

The idea is to end-up with a page that has nothing but the JSON string in it. No HTML, CSS, JS at all. Just a single line of text.

You can use document.write in JavaScript. If you call it after the page was loaded, all the content will be replaced by whatever you write.

Run your calculations on JavaScript, and then write the results using document.write . The only thing is that you will need to call it asynchronously so the page has finished loading by the time it's called; otherwise it will just append the text to the document (right after the script).

A simple way would be to call it with a setTimeout :

<html>
   <head>
      ...
   </head>
   <body>
      ...
      <script>
         // run calculations here
         ...

         // get the results into a variable
         results = RESULT_OF_THE_CALCULATIONS;

         // write the variable using a setTimeout of 1 millisecond
         setTimeout('document.write(results)', 1);
      </script>
   </body>
</html>

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