我正在尝试使用以下方法从 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/