iOS: libxml2 xpath 函数调用示例, 网页解析

在XPath中使用Contains函数

#import <Foundation/Foundation.h>

#import <libxml/HTMLparser.h>
#import <libxml/HTMLtree.h>
#import <libxml/xpath.h>
#import <libxml/xpathInternals.h>


//读取URL地址的内容
NSString * ReadURLContent(NSString *sURL, NSStringEncoding enc)
{
    NSURL *url = [NSURL URLWithString:sURL];
    NSString *sResponse = [NSString stringWithContentsOfURL:url encoding:enc error:nil];
    return sResponse;
}

//测试解析Baidu的网页
void TestParseBaidu()
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    
    //读取网页内容
    NSString *sURL = @"http://www.baidu.com";
    NSStringEncoding enc = NSUTF8StringEncoding;
    NSString *sContent = ReadURLContent(sURL, enc);
    
    //解析网页
    doc = htmlReadDoc((xmlChar *)[sContent cStringUsingEncoding:enc], NULL, NULL, HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
    if (doc == NULL) {
        printf("无法解析网页%s\n", [sURL cStringUsingEncoding: NSUTF8StringEncoding]);
        return;
    }
    
    //得到根节点
    node = xmlDocGetRootElement(doc);
    printf("根节点名称: %s\n", node->name);
    
    //使用xPath函数查找Script节点
    xmlXPathContextPtr context = NULL;
    xmlXPathObjectPtr result = NULL;
    const xmlChar *sScriptTag = (const xmlChar *)"src";
    const xmlChar *sXpath = (const xmlChar *)"//script [contains(@src,'.js')]";
    context = xmlXPathNewContext(doc);
    result = xmlXPathEvalExpression(sXpath, context);
    if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
        printf("没有选择结果\n");
    }
    
    //输出链接js脚本
    for(int i=0; i<result->nodesetval->nodeNr; i++){
        node = result->nodesetval->nodeTab[i];
        xmlChar *sScriptFile = xmlGetProp(node, sScriptTag);
        printf("%s: %s\n", node->name, sScriptFile);
        xmlFree(sScriptFile);
    }
    
    //释放内存
    xmlXPathFreeObject(result);
    xmlXPathFreeContext(context);
    xmlFreeDoc(doc);
    xmlCleanupParser();
}

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        TestParseBaidu();
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值