gpt4 book ai didi

html - 如何用QT解析HTML文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:31 26 4
gpt4 key购买 nike

目标是实现一个 QDomDocument 或类似 HTML(而非 XML)文档内容的东西。

问题是一些标签,尤其是script会触发错误:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var a = [1,2,3];
var b = (2<a.length);
</script>
</head>
<body/>
</html>

Not well formed: Element type "a.length" must be followed by either attribute specifications, ">" or "/>".

我知道 HTML 与 XML 不一样,但 Qt 对此有一个解决方案似乎是合理的:

  • 设置解析器接受 HTML
  • 另一个 HTML 类
  • 一种将一些标签名称设置为 CDATA 的方法。

我目前的尝试只实现了正常的XML解析:

QString mainHtml;

{
QFile file("main.html");
if (!file.open(QIODevice::ReadOnly)) qDebug() << "Error reading file main.html";
QTextStream stream(&file);
mainHtml = stream.readAll();
file.close();
}

QQDomDocument doc;
QString errStr;
int errLine=0, errCol=0;
doc.setContent( mainHtml, false, &errStr, &errLine, &errCol);
if (!errStr.isEmpty())
{
qDebug() << errStr << "L:" << errLine << ":" << errCol;
}

std::function<void(const QDomElement&, int)> printTags=
[&printTags](const QDomElement& elem, int tab)
{
QString space(3*tab, ' ');
QDomNode n = elem.firstChild();
for( ;!n.isNull(); n=n.nextSibling())
{
QDomElement e = n.toElement();
if(e.isNull()) continue;

qDebug() << space + e.tagName();
printTags( e, tab+1);
}
};
printTags(doc.documentElement(), 0);

注意:我想避免为此包含完整的 webkit。

最佳答案

我建议使用 htmlcxx .它根据 LPGL 获得许可。它适用于 Linux 和 Windows。如果你使用 Windows 编译 msys.

要编译它,只需提取文件并运行

./configure --prefix=/usr/local/htmlcxx
make
make install

在您的 .pro 文件中添加包含和库目录。

INCLUDEPATH += /usr/local/htmlcxx/include
LIBS += -L/usr/local/htmlcxx/lib -lhtmlcxx

使用示例

#include <iostream>
#include "htmlcxx/html/ParserDom.h"
#include <stdlib.h>

int main (int argc, char *argv[])
{
using namespace std;
using namespace htmlcxx;

//Parse some html code
string html = "<html><body>hey<A href=\"www.bbxyard.com\">myhome</A></body></html>";
HTML::ParserDom parser;
tree<HTML::Node> dom = parser.parseTree(html);
//Print whole DOM tree
cout << dom << endl;

//Dump all links in the tree
tree<HTML::Node>::iterator it = dom.begin();
tree<HTML::Node>::iterator end = dom.end();
for (; it != end; ++it)
{
if (strcasecmp(it->tagName().c_str(), "A") == 0)
{
it->parseAttributes();
cout << it->attribute("href").second << endl;
}
}

//Dump all text of the document
it = dom.begin();
end = dom.end();
for (; it != end; ++it)
{
if ((!it->isTag()) && (!it->isComment()))
{
cout << it->text() << " ";
}
}
cout << endl;
return 0;
}

示例的致谢: https://github.com/bbxyard/sdk/blob/master/examples/htmlcxx/htmlcxx-demo.cpp

您不能对 HTML 使用 XML 解析器。您可以使用 htmlcxx 或将 HTML 转换为有效的 XML。然后你就可以自由使用QDomDocument、Qt XML解析器等了。

QWebEngine也有解析功能,但是给应用带来了很大的开销。

关于html - 如何用QT解析HTML文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49223317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com