【问题标题】:Get the source DOM/HTML of an external page from URL从 URL 获取外部页面的源 DOM/HTML
【发布时间】:2020-02-15 11:41:24
【问题描述】:

我想从 Chrome 扩展中的 url 下载页面的源代码。

我有这样的东西。但不知道如何将文本格式化为html。 或者如果这种格式有效,如何在控制台中显示源代码。

fetch('https://www.transfermarkt.com/robert-lewandowski/profil/spieler/38253').then(r => r.text()).then(result => {
  // Result now contains the response text, do what you want...
  console.log("Fetch result: " + result);
  var parser = new DOMParser();
  var source_code = parser.parseFromString(result, "text/html");
  console.log("Source code: " + source_code);
});

例如,我想从跨度“dataValue”中获取文本。 我怎样才能做到这一点?

【问题讨论】:

  • @mplungjan 那么如何使用 getElementByClass 或其他东西从中获取一些东西。
  • 看我的回答......

标签: javascript html dom google-chrome-extension


【解决方案1】:

下面的第一个console.log是文本表示。

第二个是 DOM 对象,您可以在其中显示要显示的内容。

fetch('https://www.transfermarkt.com/robert-lewandowski/profil/spieler/38253').then(r => r.text()).then(result => {
  // Result now contains the response text, do what you want...
  // console.log("Source code: " + result); // textual representation
  var parser = new DOMParser();
  var DomObject = parser.parseFromString(result, "text/html");
  console.log("Name: " + DomObject.querySelector("title").textContent);
  [...DomObject.querySelectorAll(".dataItem")].forEach(item => {
    if (item.textContent.trim() === "Joined:") {
      console.log("Joined:",item.nextElementSibling.textContent);
    }
  });
})

附:不要忘记在 manifest.json 中添加站点(或 "<all_urls>"):

  • ManifestV2:"permissions": ["*://*.transfermarkt.com/"]
  • ManifestV3:"host_permissions": ["*://*.transfermarkt.com/"]

【讨论】:

  • 有一个更新我认为更精确的问题。如果您可以提供示例代码如何实现,我应该能够处理其余部分。
猜你喜欢
  • 2011-07-14
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 2013-12-26
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多