iOS 中使用JS提取网页数据,自动提交表单等

1.首先用一个webview加载网页

    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

    webView.delegate = self;

    [self.view addSubview:webView];


    NSURL *url =[[NSURL alloc] initWithString:@"http://www.reg007.com"];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    [webView loadRequest:request];


2.自动提交表单

    NSString *ret = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='18666666666';"];

    NSLog(@"%@", ret);

    ret = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit(); "];

    NSLog(@"%@", ret);


3.分析网页数据

    NSString *count = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('li').length;"];

    

     NSLog(@"%d  %@", 0, count);

    if (!count) {

        return;

    }

    

    for (int i=0; i<[count intValue]; i++) {

        NSString *classType = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByTagName('li')[%d].getAttribute(\"class\");", i]];

        if ([classType isEqualToString:@"media"]) {

             NSLog(@"%d  %@\n", i+1, count);

            NSString *name = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByTagName('li')[%d].childNodes[1].childNodes[0].childNodes[0].textContent;", i]];

            NSString *href = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByTagName('li')[%d].childNodes[1].childNodes[0].childNodes[0].href;", i]];

            NSString *desc = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByTagName('li')[%d].childNodes[1].childNodes[3].textContent;", i]];

            

            NSLog(@"name: %@, href:%@, desc:%@\n\n", name, href, desc);

        }

    }


你可能感兴趣的:(IOS)