javascript - 如何解决解析 HTML 时出现错误

标签 javascript google-apps-script web-scraping html-parsing

我正在尝试使用以下方法从 Google 电子表格中的网页获取元素:

function pegarAsCoisas() {
  var html = UrlFetchApp.fetch("http://www.saosilvestre.com.br").getContentText();
  var elements = XmlService.parse(html);                 
}

但是我不断收到错误:

Error on line 2: Attribute name "itemscope" associated with an element type "html" must be followed by the ' = ' character. (line 4, file "")

如何解决这个问题?我想从此网站获取 H1 文本,但对于其他网站,我必须选择其他元素。

我知道方法 XmlService.parse(html) 适用于其他网站,例如维基百科。如您所见here .

最佳答案

html 不是 xml。而且您不需要尝试解析它。您需要使用字符串方法:

function pegarAsCoisas() {

  var urlFetchReturn = UrlFetchApp.fetch("http://www.saosilvestre.com.br");
  var html = urlFetchReturn.getContentText();

  Logger.log('html.length: ' + html.length);

  var index_OfH1 = html.indexOf('<h1');
  var endingH1 = html.indexOf('</h1>');

  Logger.log('index_OfH1: ' + index_OfH1);
  Logger.log('endingH1: ' + endingH1);

  var h1Content = html.slice(index_OfH1, endingH1);
  var h1Content = h1Content.slice(h1Content.indexOf(">")+1);

  Logger.log('h1Content: ' + h1Content);

};

关于javascript - 如何解决解析 HTML 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33927307/

相关文章:

javascript - 在 'selected tab index' 上获取 'active tab change' - devexpress 功能区

php - 从谷歌抓取关键字建议

php - 如何最好地在 PHP 中搜索网站并检索数据?

javascript - 使用 Puppeteer 单击后检测 POST 响应到达

javascript - 为什么 wp_enqueue_style 在这里不起作用?

php - 动态表单创建向下添加行

javascript - 使用jquery处理503错误

google-apps-script - 谷歌电子表格脚本,为一个单元格提供多个超链接选择

javascript - Google 脚本 - 为什么 for 循环中的 copyTo 不起作用?

google-apps-script - 触发函数和 IMPORTRANGE