javascript - 从 http 响应中获取 API : Get title, 关键字和正文

标签 javascript web-scraping

我想知道使用 fetch api ( Is there a way to not send cookies when making an XMLHttpRequest on the same origin? ) 从 responseText 中获取用户可见的标题、关键字和内容的最佳方法是什么

目前,我使用正则表达式从响应文本中获取标题,例如:

var re_title = new RegExp("<title>[\n\r\s]*(.*)[\n\r\s]*</title>", "gmi");
var title = re_title.exec(responseText);
if (title)
    title = title[1]

要获取关键字元标记中的内容,我需要使用几个正则表达式。

为了让内容对用户可见,我们不需要 script、div 等标签,也不需要 script 标签之间的文本。这是为了仅获取响应正文中有意义的词。

我认为(也根据各种 stackoverflow 帖子)为此使用正则表达式并不是正确的方法。有什么替代方案?

最佳答案

作为zzzzBov前面提到,您可以使用浏览器的 DOMParser API 实现,通过解析 fetch 请求的 response.text() 来实现此目的。下面是一个为自己发送此类请求并解析标题、关键字和正文文本的示例:

<!DOCTYPE html>
<html>

<head>
  <title>This is the page title</title>
  <meta charset="UTF-8">
  <meta name="description" content="Free Web Help">
  <meta name="keywords" content="HTML,CSS,XML,JavaScript">
  <meta charset="utf-8">
  <script>
    fetch("https://dl.dropboxusercontent.com/u/76726218/so.html")
      .then(function(response) {
        return (response.text());
      })
      .then(function(responseText) {
        var parsedResponse = (new window.DOMParser()).parseFromString(responseText, "text/html");
        document.getElementById("title").innerHTML = "Title: " + parsedResponse.title;
        document.getElementById("keywords").innerHTML = "Keywords: " + parsedResponse.getElementsByName("keywords")[0].getAttribute("content");
        document.getElementById("visibleText").innerHTML = "Visible Text: " + parsedResponse.getElementsByTagName("body")[0].textContent;
      });
  </script>
</head>

<body>

  <div>This text is visible to the user.</div>
  <div>So <i>is</i>  <b>this</b>.</div>
  <hr>
  <b>Results:</b>
  <ul id="results">
    <li id="title"></li>
    <li id="keywords"></li>
    <li id="visibleText"></li>
  </ul>

</body>

</html>

我在 Fetch API 上找到了 Mozilla 的文档, Using Fetch , 和 Fetch basic concepts有帮助。

关于javascript - 从 http 响应中获取 API : Get title, 关键字和正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32210341/

相关文章:

python - 从 BeautifulSoup 结果集中提取 <li> 标签

javascript - 使用 (function() { … }).call(this) 包装文件与使用简单 () 进行调用

javascript - 右键单击 div 时未打开上下文菜单

javascript - 限制动态动画中的 FPS

javascript - 在 javascript 中用指数格式化数字?

python - 如何使用 BeautifulSoup 处理特定标签中的不同格式

javascript - Java2Javascript中\u000D\u000A的正确转换

python - 在 Python 中使用 Selenium 抓取随时间变化的动态 URL

python - 将从 HTML 表中抓取的数据写入 CSV 文件

python - 使用 BeautifulSoup 获取 youtube 描述?