所以我在类文件中包含以下代码:
Document requestData (String url, [String postVars, bool pauseApp = false, onSuccess(Document ht)]) {
HttpRequest html = new HttpRequest();
html.open((postVars == null ? 'GET' : 'POST'), url, async: !pauseApp);
html.send(postVars);
if (pauseApp == true) { return html.responseXML; }
else { html.on.readyStateChange.add((Event e) {
if (html.readyState == HttpRequest.DONE && (html.status == 200 || html.status == 0)) {
try {
//HERE IS WHERE THE ISSUE IS ----V
DOMParser d = new DOMParser();
onSuccess(d.parseFromString(html.responseText,"text/html"));
}
catch (e) {
print("Error on requestData($url) async = $pauseApp - $e");
}
}
});
}
}
(整个引用来源:http://pastebin.com/z21PM7r0 - 我正在使用 dartium 标志“--disable-web-security”来允许跨服务器请求)
问题基本上是,请求responseXML 返回null,而responseText 按预期返回HTML。为了解决这个问题,我尝试使用 DOM 解析器,但失败了。
由于我不拥有或控制我需要连接的服务器,因此我无法自己修复 html。我认为问题是因为它格式错误。
这是我尝试使用上面的函数解析的网站的代码: http://pastebin.com/KvMN9AuF
W3 验证器给出:193 个错误,16 个警告
有人知道如何解决这个问题吗?或者这是我必须放弃的事情......
最佳答案
尝试html5lib 。它是纯 Dart 中符合规范的 html5 解析器。您应该能够读取格式错误的 html,然后使用 document.outerHtml 获取格式正确的字符串。
关于html - 使用 Dart 解析格式错误的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761443/