Get only text and images from <div> in Objective-C

一笑奈何 提交于 2019-12-11 17:46:22

问题


I'm making a news reading application. The best site I found was http://fulltextrssfeed.com/ It takes the text and images from any webpage and gives back clean text. As they don't have an API I need some way to get the data from the <div>. This is the div ID:

<div id="preview">

How can I leach onto the feed and get only its content (It would be a plus if there are no HTML tags, if there is I can make a work around.)


回答1:


I'm not sure about your question, but if you're using obj-c, I really recommend Hpple. It's a really good XML/HTML parser.

To use it, you'll need to add ${SDKROOT}/usr/include/libxml2 in "Header Search Path", in your project option and add -lxml2 to "Other Linker Flag".

Then, when you already have the Hpple files, drag it to your code: TFHpple.h, TFHpple.m, TFHppleElement.h, TFHppleElement.m, XPathQuery.h, XPathQuery.m.

In the code (To get your div "preview"), add:

NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: @"http://www.yoursite.com/index.html"]] dataUsingEncoding:NSUTF8StringEncoding];

TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements  = [xpathParser searchWithXPathQuery:@"//div[@id='preview']"]; // Here we use 
TFHppleElement *element = [elements objectAtIndex:0];
NSString *string = [element content];
NSLog(@"%@", string);

[xpathParser release];
[htmlData release];

Now we have the "preview div" with Hpple. To get some subclass (as p or a), use it:

NSArray *elements  = [xpathParser searchWithXPathQuery:@"//div[@id='preview']/p/text()"]; 

To undertand more, take a look at XPath Syntax. Also check a tutorial.

Hope it help.




回答2:


I use this to strip all html very succesfully

NSString + Strip HTML



来源:https://stackoverflow.com/questions/10774737/get-only-text-and-images-from-div-in-objective-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!