我試圖解析下面用TouchXML呈現的HTML,但是當我嘗試提取某些屬性時它會一直崩潰。我對解析器世界完全陌生,因此對於成爲一名完全白癡而道歉。我需要幫助來解析這個HTML。我試圖完成的是解析每個屬性和值或不是什麼,並將它們複製到一個字符串。我一直在試圖找到一個很好的解析器來解析HTML,我相信TouchXML是我見過的最好的,因爲Tidy。說起Tidy,我怎麼能通過Tidy先運行這個HTML然後解析它?我不知道如何做到這一點。這裏是我迄今爲止沒有用的代碼,因爲它沒有從HTML中提取我需要的所有東西。任何幫助或建議將不勝感激。由於如何使用TouchXML或其他替代方法解析HTML
我當前的代碼:需要解析
NSMutableArray *res = [[NSMutableArray alloc] init];
// using local resource file
NSString *XMLPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"example.html"];
NSData *XMLData = [NSData dataWithContentsOfFile:XMLPath];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:XMLData options:0 error:nil] autorelease];
NSArray *nodes = NULL;
nodes = [doc nodesForXPath:@"//div" error:nil];
for (CXMLElement *node in nodes) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setObject:[[node attributeForName:@"id"] stringValue] forKey:@"id"];
[res addObject:item];
[item release];
}
NSLog(@"%@", res);
[res release];
HTML文件:
<html>
<head>
<base target="_blank" />
</head>
<body style="margin:2;">
<div id="group">
<div id="groupURL"><a href="http://www.example.com/groups">Group URL</a></div>
<img id="grouplogo" src="http://images.example.com/groups/image.png" />
<div id="groupcomputer"><a href="http://www.example.com/groups/page" title="Group Title">Group title this would be here</a></div>
<div id="groupinfos">
<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>
<div id="groupinfo-l">Years</div><div id="groupinfo-r">4 years</div>
<div id="groupinfo-l">Salary</div><div id="groupinfo-r">100K</div>
<div id="groupinfo-l">Other</div><div id="groupoth" style="width:15px">other info</div>
</body>
</html>
編輯:我可以用元素分析器,但我需要知道如何從中提取這個人的名字在這種情況下,下面的例子將是Ralph。
<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>
我試過元素分析器,但我無法獲得某些數據。例如,假設我正在嘗試獲取「groupURL」鏈接的文本。我似乎無法得到它。我可以很好地獲取URL,但我無法獲取鏈接的組URL標題。這是我的代碼:\t Element * aTag = [document selectElement:@「a」]; \t NSString * href = [aTag屬性:@「href」]; NSLog(@「%@」,href); – 0SX 2010-12-19 17:51:51
我不在我的Mac上,所以我不能給你確切的代碼,但是如果你想獲得「groupURL」元素的文本,你應該調用[yourElement contentsText]或[yourElement getChildsContentsText:@「your child」 ]。無論如何,嘗試與他們中的一個,明天我將能夠給你準確的解決方案。 – ender 2010-12-19 18:41:05
感謝您的提示,我會看看我是否可以獲取文本。如果你還記得,如果你不介意,明天你還可以發佈確切的代碼。謝謝 – 0SX 2010-12-19 19:40:34