I'm trying to automate interaction with an old web interface that currently only exposes user-driven forms, so I need to scrape some information from a web page with a dynamic request.
If I use an XHR, I can treat the response as a Document
, which lets me use methods like querySelector
to retrieve information from specific nodes. I'd like to try to use the Fetch API, though, which only gives me a Body. This has blob
, formData
, json
, and text
, but I don't see anything that would let me treat it as a Document
.
Am I missing something? Can I get a Document or something else query-able directly from fetch
? If not, is there a simple way to take a string (from Body.text()
) and turn it into a Document?
The trick is to use the text() method instead of the json() method on the stream. This will return a text string of the HTML. fetch('/about'). then(function (response) { // The API call was successful!
This is the first method called in our fetch() chain, if it resolves, we then call our json() method which again returns a Promise from the response. json() call. After this we have an object of the parsed JSON. If the parsing fails the Promise is rejected and the catch statement executes.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
Can I get a Document or something else query-able directly from fetch? If not, is there a simple way to take a string (from Body.text()) and turn it into a Document?
You can’t get a Document back directly from the Fetch API itself. But you can use DOMParser
and give its parseFromString()
method the text the Fetch Body.text()
promise resolves to.
fetch("https://enable-cors.org/")
.then(response => response.text())
.then(text => {
const parser = new DOMParser();
const htmlDocument = parser.parseFromString(text, "text/html");
const section = htmlDocument.documentElement.querySelector("section");
document.querySelector("div").appendChild(section);
})
<div></div>
async function fetchDocument(url) {
let response = await fetch(url);
let text = await response.text();
if (!fetchDocument.parser) fetchDocument.parser = new DOMParser(); // the dom parser is reusable
return fetchDocument.parser.parseFromString(text, "text/html");
}
let doc = await fetchDocument(urlToFetch)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With