Cod*_*rer 7 javascript fetch-api
我正在尝试自动化与旧的Web界面进行交互,该界面目前只暴露用户驱动的表单,因此我需要从带有动态请求的网页中抓取一些信息.
如果我使用XHR,我可以将响应视为a Document,这使我可以使用类似方法querySelector从特定节点检索信息.我想尝试使用Fetch API,它只给我一个Body.这blob,formData,json,和text,但我没有看到任何东西,会让我把它作为一个Document.
我错过了什么吗?我可以直接从中查询文档或其他内容fetch吗?如果没有,是否有一种简单的方法来获取字符串(从Body.text())并将其转换为文档?
sid*_*ker 11
我可以直接从fetch中获取文档或其他可查询的内容吗?如果没有,是否有一种简单的方法来获取字符串(来自Body.text())并将其转换为文档?
你不能得到一个文件从获取API本身直接返回.但是您可以使用Fetch promise解析的文本DOMParser并为其parseFromString方法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);
})Run Code Online (Sandbox Code Playgroud)
<div></div>Run Code Online (Sandbox Code Playgroud)