UIWebView检索链接并导航到它

时间:2013-03-21 01:08:43

标签: javascript ios objective-c uiwebview nsregularexpression

我正在为我的应用添加UIWebView,该应用应加载受密码保护的网页。然后,它应该自动从该页面中选择一个链接并导航到该页面。此网站不断更改其链接,因此无法选择目标网页的URL。我需要先登录,然后从主页面中选择一个链接。

如何在登录所需链接后编写代码以搜索我的主页面并导航到该页面?

2 个答案:

答案 0 :(得分:1)

您可以使用Javascript按其ID检索链接,然后加载它:

[yourWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('yourLinkID').click();"];

要查找链接的id是什么,请在页面上检查其html标记以获取id属性的值。

答案 1 :(得分:0)

我认为Regular Expressions会有所帮助。

//NSError will handle errors
NSError *error;
//Create URL for you page. http://example.com/index.php just an example
NSURL *pageURL = [NSURL URLWithString:@"http://example.com/index.php"];
//Retrive page code to parse it using regex
NSString *pageHtml = [NSString stringWithContentsOfURL:pageURL           
                                              encoding:NSUTF8StringEncoding 
                                                 error:&error];
if (error)
{
    NSLog(@"Error during retrieving page HTML: %@", error);
    //Will terminate your app
    abort();
    //TODO: handle connection error here
}
error = nil;
//Creating regex to parsing page html
//Information about regex patters you can easily find.
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"<a[^>]*href=\"([^\"]*)\"[^>]*>mylink</a>"
                                                                  options:NSRegularExpressionCaseInsensitive
                                                                    error:&error];
if (error)
{
    NSLog(@"Error during creating regex: %@", error);
    //Will terminate your app
    abort();
    //TODO: handle regex error here
}
//Retrieving first match of our regex to extract first group
NSTextCheckingResult *match = [regex firstMatchInString:pageHtml
                                                options:0
                                                  range:NSMakeRange(0, [pageHtml length])];
NSString *pageUrl = [pageHtml substringWithRange:[match rangeAtIndex:1]];
NSLog(@"Page URL = %@", pageUrl);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pageUrl]]];

如果您的UIWebView已下载页面包含HTML,则可以替换

NSURL *pageURL = [NSURL URLWithString:@"http://example.com/index.php"];
NSString *pageHtml = [NSString stringWithContentsOfURL:pageURL encoding:NSUTF8StringEncoding error:&error];

用这个:

NSString *pageHtml = [webview stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];