简体   繁体   English

如何从UIWebView获取内容?

[英]How can I get the content from a UIWebView?

I need to get the first paragraph of each page from a UIWebView . 我需要从UIWebView获取每个页面的第一段。 How can I get this? 我怎么能得到这个?

I have also one code for regular expression detection, but it gives the paragraph class name instead of paragraph contents: 我还有一个用于正则表达式检测的代码,但是它给出了段落类名而不是段落内容:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<p\\s[\\s\\S]*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?"
                             options:NSRegularExpressionCaseInsensitive
                             error:&error];

[regex enumerateMatchesInString:html
                        options:0
                        range:NSMakeRange(0, [html length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSString *img = [html substringWithRange:[result rangeAtIndex:2]];
    NSLog(@"img src %@",img);
}];

NSString *classs=[webView stringByEvaluatingJavaScriptFromString:@"document.getElementbyClassName(img)"];

The most robust way to do this is to execute some javascript code in the context of the web view which locates the first paragraph element in the document and returns its text. 最可靠的方法是在Web视图的上下文中执行一些javascript代码,该代码在文档中找到第一段元素并返回其文本。 You can do this using UIWebView 's stringByEvaluatingJavaScriptFromString method. 您可以使用UIWebViewstringByEvaluatingJavaScriptFromString方法执行此操作。

The code below starts off by retrieving an array of all elements in the document with the tag name P (this assumes the text you are looking for is in these elements, if not you'll have more work to do). 下面的代码通过检索标签名称为P的文档中所有元素的数组开始(这假设您要查找的文本位于这些元素中,否则,您将需要做更多的工作)。 It then checks if there is at least one paragraph element, and if so, it returns its text content. 然后,它检查是否存在至少一个段落元素,如果存在,则返回其文本内容。 Otherwise, it returns the empty string. 否则,它返回空字符串。

- (void)webViewDidFinishLoad:(UIWebView *)_webView
{
    NSString *code = @"var paragraphs = document.getElementsByTagName('P');"
                      "paragraphs.length > 0 ? paragraphs[0].innerText : '';";
    NSString *text = [_webView stringByEvaluatingJavaScriptFromString: code];
    // ... do something with text ...
}

You can run arbitrary javascript code in the context of the web view if you want to examine or change other aspects of the document. 如果要检查或更改文档的其他方面,可以在Web视图的上下文中运行任意javascript代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM