为什么 javascript 不从 fetch 中解析 HTML?

max*_*max 5 javascript dom fetch

我正在创建一个 chrome 扩展,可以从各个网站抓取照片。我有每个网站的 URL,我想获取并解析这些网站,然后img按类或 ID 获取特定元素。

我使用 Javascriptfetch()函数来DOMParser解析 HTML,它成功返回文档,但任何 DOM 查询都会返回空的 NodeLists / HTMLCollections。

fetch("www.example.com")
.then(res => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(res, "text/html");
    console.log(htmlDoc.querySelectorAll('h1'))
})
Run Code Online (Sandbox Code Playgroud)

这给了我一个空的 NodeList。为什么??我怎样才能获得我正在寻找的元素?

Ran*_*urn 7

在使用响应之前,您需要解析它。像这样:

fetch("//randycasburn.com")
  .then(res => res.text())
  .then(html => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(html, "text/html");
    console.log(htmlDoc.querySelector('span').textContent)
  })
Run Code Online (Sandbox Code Playgroud)

否则,通过传递res自身,将创建一个 DOM 并将res其转换为字符串 ( [object Response]),这将产生此 DOM:(注意没有 H1)

<html>
  <head></head>
  <body>[object Response]</body>
</html>
Run Code Online (Sandbox Code Playgroud)