Javascript UIWebView检索链接并导航到它

Javascript UIWebView检索链接并导航到它,javascript,ios,objective-c,uiwebview,nsregularexpression,Javascript,Ios,Objective C,Uiwebview,Nsregularexpression,我正在将UIWebView添加到我的应用程序中,该应用程序应加载受密码保护的网页。然后,它应该自动从该页面选择一个链接并导航到该页面。此网站不断更改其链接,因此无法选择所需页面的URL。我需要先登录,然后从主页上选择一个链接 如何编写代码,在登录后搜索主页上所需的链接并导航到它?我认为这会有所帮助 //NSError will handle errors NSError *error; //Create URL for you page. http://example.com/index.php

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

如何编写代码,在登录后搜索主页上所需的链接并导航到它?

我认为这会有所帮助

//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]]];
为此:

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

您可以使用Javascript通过其id检索链接,然后加载它:

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

要查找链接的id,请查看页面上的html标记,以了解id属性的值。

非常感谢您的快速回复。我应该解释一下,我对编程相当陌生。我搜索了有关正则表达式的信息。例如,我能用它在页面上找到一个名为mylink的链接,并导航到该链接不断变化的url吗?再次感谢链接名称始终保持不变,但该链接的url不断变化。请检查编辑的答案。如果此代码不起作用,请发布您的网站url进行检查。非常感谢您的帖子。这正是我想要的,也是一个很大的帮助!我无法告诉你我有多感激你。向你问好,阿利希·谢尔盖,我想知道你是否能帮我一个相关的方式。我已经在我的WebViewDidFinishLoad方法中包含了正则表达式,并且一切正常,除了在导航到目标网页之后,似乎有一个无限循环,页面变为空白。当我做一个NSLog时,它似乎总是无限地重复WebPageDidFinishLoad方法。我做错什么了吗?谢谢
[yourWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('yourLinkID').click();"];