您的位置:首页 > 其它

hpple使用几个注意点

2014-01-13 20:35 387 查看
hpple功能有限,使用的时候要注意一个原则:如果页面复杂,节点较多,解析的html需要先截取,xpath路径尽可能短,使用简单语法。

XPath语法不再赘述,本文的话题是分析得到的一个TFHppleElement数组。

对于数组里的某个TFHppleElement可能有如下结构:

{
nodeChildArray =     (
{
nodeContent = "\n        \U00a0";
nodeName = text;
},
{
nodeAttributeArray =             (
{
attributeName = href;
nodeContent = "/character/ch0146096/?ref_=ttfc_fc_cl_t1";
}
);
nodeChildArray =             (
{
nodeContent = "Tyrion Lannister";
nodeName = text;
}
);
nodeName = a;
},
{
nodeContent = "\n                  (28 episodes, 2011-2013)\n              ";
nodeName = text;
}
);
nodeName = div;
}


一个完备的节点一般包括属性数组,子节点数组,节点名三部分。一个节点的类型由节点名字决定。像上面就包含了div,a和text三种节点。任一节点是字典类型的。

假设我们令elem为指向上述结构的指针,则

[elem children];得到子节点数组

[elem childrenWithTagName:@"text"];可以得到div节点的所有文本子节点。

[elem firstChildrenWithTagName:@"text"];则可以得到div节点的第一个文本节点。

[elem tagName]; 则得到@"div"

[elem attributes];可以得到div的属性字典,显然这里没

这里我们引入指向子节点a的指针a,则

[a objectForKey:@“href”];得到@"/character/ch0146096/?ref_=ttfc_fc_cl_t1"

[a firstTextChild]content]; 得到@“"Tyrion Lannister"

[a text];此处和上句效果一致,返回第一个文本节点的内容

但是[elem text]为@"\n \U00a0"

本例中我们没用到- (NSArray*) childrenWithClassName:(NSString*)className和- (TFHppleElement *) firstChildWithClassName:(NSString*)className

显然class和tagName是地位等同的,对于如下情况,我们就可以使用上述方法

<html>
<head>
<style type="text/css">
h1.intro {color:blue;}
p.important {color:green;}
</style>
</head>

<body>
<h1 class="intro">Header 1</h1>
<p>A paragraph.</p>
<p class="important">Note that this is an important paragraph.</p>
</body>
</html>


设elem指向body节点,[elem childrenWithClassName:@"intro"]打印出来就是:

elem is (
"{\n    nodeAttributeArray =     (\n
{\n            attributeName = class;\n            nodeContent = intro;\n        }\n    );
\n    nodeChildArray =     (\n
{\n            nodeContent = \"Header 1\";\n            nodeName = text;\n        }\n    );
\n    nodeName = h1;\n}"
)


补充一点,对于a的某个属性节点,结构为

{
nodeChildArray =     (
{
nodeContent = "/character/ch0146096/?ref_=ttfc_fc_cl_t1";
nodeName = text;
}
);
nodeName = href;
}


一个属性节点没有属性数组,只有文本子节点数组和节点名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: