libtidy解析html文档,百度搜索结果HTML分析

博客讲述了在Qt环境下,由于QDomDocument和QXmlStreamReader无法有效解析HTML,作者转向使用TidyLib这个库来纠正和清理HTML文档,以便于解析百度搜索结果。通过TidyLib,可以将HTML转换为XHTML并进行格式化,从而成功提取搜索结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:

为了从搜索结果中提取所有网页,以备后续处理。

访问百度链接分析 名称 值 说明

wd 任意文字 关键字

rn 可以不指定,默认为10,最大为50,最小为1,可设置为任意值 一页包含的结果条目数

pn 百度默认显示760条,所以最后一页为pn=750 第一条结果的索引位置

示例:

关键字:老虎,第10条记录,每页显示3条。所以打开的是以老虎为关键字,第四页的记录

HTML源文件分析

刚下载的html源文件格式非常混乱,可使用在线html格式化工具进行格式化,以便阅读。

根据我的需求,在HTML文件中,

20180315224320130793.png

20180315224320471591.png

提取搜索结果(QT实现)

在Qt中,使用QDomDocument 或 QXmlStreamReader 来解析 html 文件都失败了。经分析,其原因是:QDomDocument 或 QXmlStreamReader都是针对解析XML文件设计的。HTML与XML的区别

经过查找资料,TidyLib 库正好可以解决问题。

Tidy is a console application for Mac OS X, Linux, Windows, UNIX, and more. It corrects and cleans up HTML and XML documents by fixing markup errors and upgrading legacy code to modern standards.

libtidy is a C static and dynamic library that developers can integrate into their applications in order to bring all of Tidy’s power to your favorite tools. libtidy is used today in desktop applications, web servers, and more.

TidyLib使用代码如下:

bool HtmlParse::setDatas(const QByteArray &datas)

{bool result = false;

TidyBuffer output= {0};

TidyBuffer errbuf= {0};int rc = -1;

Bool ok;

TidyDoc tdoc= tidyCreate(); //Initialize "document"

ok= tidyOptSetBool( tdoc, TidyXhtmlOut, yes ); //Convert to XHTML

if( ok )

rc= tidySetErrorBuffer( tdoc, &errbuf ); //Capture diagnostics

if ( rc >= 0)

rc= tidyParseString( tdoc, datas.data() ); //Parse the input

if ( rc >= 0)

rc= tidyCleanAndRepair( tdoc ); //Tidy it up!

if ( rc >= 0)

rc= tidyRunDiagnostics( tdoc ); //Kvetch

if ( rc > 1 ) //If error, force output.

rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1);if ( rc >= 0)

rc= tidySaveBuffer(tdoc, &output); //Pretty Print

if ( rc >= 0)

{if (doc.setContent(QByteArray((char *)output.bp))) //QDomDocument doc;

{

result= true;

}

}

tidyBufFree(&output );

tidyBufFree(&errbuf );

tidyRelease( tdoc );returnresult;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值