我正在爲我的應用程序添加一個UIWebView
,該應用程序應加載受密碼保護的網頁。然後它應該自動從該頁面選擇一個鏈接並導航到該頁面。本網站不斷更改鏈接,因此無法選擇目標網頁的網址。我需要先登錄,然後從主頁面選擇一個鏈接。UIWebView檢索一個鏈接並導航到它
如何編寫代碼以便在登錄後查找我的主頁並找到所需的鏈接?
我正在爲我的應用程序添加一個UIWebView
,該應用程序應加載受密碼保護的網頁。然後它應該自動從該頁面選擇一個鏈接並導航到該頁面。本網站不斷更改鏈接,因此無法選擇目標網頁的網址。我需要先登錄,然後從主頁面選擇一個鏈接。UIWebView檢索一個鏈接並導航到它
如何編寫代碼以便在登錄後查找我的主頁並找到所需的鏈接?
我認爲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"];
您可以使用JavaScript通過ID檢索鏈接,然後加載它:
[yourWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('yourLinkID').click();"];
要查找鏈接的id,請在頁面上檢查其id屬性值的html標記。
簡單是關鍵:) – Krease 2013-03-21 06:46:14
非常感謝您的快速回復。我應該解釋說我對編程很陌生。我搜索關於正則表達式的信息。我能用這個例子在頁面上找到一個名爲mylink的鏈接並導航到該鏈接的不斷變化的url?再次感謝你 – 2013-03-21 01:32:39
鏈接名稱始終保持不變,但該鏈接的URL不斷變化。 – 2013-03-21 01:33:30
查看編輯答案。如果此代碼不起作用,請發佈您的網站網址進行檢查。 – 2013-03-21 01:59:03