本文参考:
HTML解析库Gumbo的使用(一)
c++解析html
C++解析网页常用的库:htmlcxx,基于gumbo的html解析库
htmlcxx经过实测发现对于html解析不友好,例如无法解析",以及部分网页解析出错。
下面是基于gumbo的html解析库的实测用例:
git:https://github.com/jeflib/cjhtmlparser
- 通过标签的id查找指定标签:
find("a#123"),查找标签<a id="123"> </a> - 通过标签的class查找指定标签:
find("a.123"),查找标签<a class="123"> </a> - 查找指定标签:
find("a"),查找标签<a > </a>
std::string content("<h1><a id=\"123\">wrong link</a><a class=\"special\"\\>some link</a></h1>");
printf("%s\r\n", content.c_str());
CDocument doc;
doc.parse(content);
CSelection c = doc.find("a");
printf("\r\n*****************find(\"a\")**********************************\r\n");
for (int i = 0; i < c.nodeNum(); ++i)
{
CNode nd = c.nodeAt(i);
std::string ref = nd.ownText();
printf("find label:%s,href:%s\r\n", nd.tag().c_str(), ref.c_str());
}
printf("\r\n*****************find(\"a#123\")**********************************\r\n");
c = doc.find("a#123");
for (int i = 0;i < c.nodeNum();++i)
{
CNode nd = c.nodeAt(i);
std::string ref = nd.ownText();
printf("find label:%s id=\"123\",href:%s\r\n", nd.tag().c_str(), ref.c_str());
}
printf("\r\n*****************find(\"a.special\")**********************************\r\n");
c = doc.find("a.special");
for (int i = 0; i < c.nodeNum(); ++i)
{
CNode nd = c.nodeAt(i);
std::string ref = nd.ownText();
printf("find label:%s class=\"special\",href:%s\r\n", nd.tag().c_str(), ref.c_str());
}

本文介绍了在C++中使用Gumbo库解析HTML的问题,指出htmlcxx库的不足,并提供了Gumbo库的实例,展示了如何通过标签ID、类名或标签本身来查找HTML元素。

1万+

被折叠的 条评论
为什么被折叠?



