我可以对 Fetch API 响应使用 DOM 查询方法吗?
Can I use DOM query methods against a Fetch API response?
我正在尝试自动与当前仅公开用户驱动的表单的旧 Web 界面进行交互,因此我需要使用动态请求从网页中抓取一些信息。
如果我使用 XHR,我可以将响应视为 Document
,这让我可以使用 querySelector
之类的方法从特定节点检索信息。不过,我想尝试使用 Fetch API,它只会给我一个 Body。这有 blob
、formData
、json
和 text
,但我没有看到任何可以让我将其视为 Document
的东西。
我错过了什么吗?我可以直接从 fetch
获取文档或其他可查询的内容吗?如果没有,是否有一种简单的方法来获取字符串(来自 Body.text()
)并将其转换为文档?
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?
您无法获得 Document back directly from the Fetch API itself. But you can use DOMParser
and give its parseFromString()
method the text the Fetch Body.text()
承诺解决。
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)
我正在尝试自动与当前仅公开用户驱动的表单的旧 Web 界面进行交互,因此我需要使用动态请求从网页中抓取一些信息。
如果我使用 XHR,我可以将响应视为 Document
,这让我可以使用 querySelector
之类的方法从特定节点检索信息。不过,我想尝试使用 Fetch API,它只会给我一个 Body。这有 blob
、formData
、json
和 text
,但我没有看到任何可以让我将其视为 Document
的东西。
我错过了什么吗?我可以直接从 fetch
获取文档或其他可查询的内容吗?如果没有,是否有一种简单的方法来获取字符串(来自 Body.text()
)并将其转换为文档?
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?
您无法获得 Document back directly from the Fetch API itself. But you can use DOMParser
and give its parseFromString()
method the text the Fetch Body.text()
承诺解决。
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)