ios webView获取html标签

描述 最近项目开发 有一个需要获取html标签的需求 ,对标签中的url进行操作
一 . 首先创建webView 使用懒加载

  • (UIWebView )webView {
    if (!_webView) {
    _webView = [[UIWebView alloc] initWithFrame:RECT(0, heightWebView + 44, SCREENWIDTH, SCREENHEIGHT- (heightWebView) - 44)];
    _webView.delegate = self;
    _webView.opaque = NO;
    _webView.scalesPageToFit =YES;
    _webView.backgroundColor = [UIColor whiteColor];
    if (@available(ios 11.0,
    )){ _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;}
    }
    return _webView;
    }
    二 . 加载webView
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@“https://www.baidu.com”] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.f]];
    三 . 实现webView的代理方法
  • (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest
    *)request navigationType:(UIWebViewNavigationType)navigationType;
    //UIWebView开始加载
  • (void)webViewDidStartLoad:(UIWebView *)webView;
    //UIWebView加载完成
  • (void)webViewDidFinishLoad:(UIWebView *)webView;
    //UIWebView加载失败
  • (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
    *四 . 在- (void)webViewDidFinishLoad:(UIWebView )webView;代理方法中获取想要的内容进行操作

NSString *title = [webView stringByEvaluatingJavaScriptFromString:@“document.title”];//标题
NSString *text = [webView stringByEvaluatingJavaScriptFromString:@“document.documentElement.innerText”];//页面信息
NSString *url = [webView stringByEvaluatingJavaScriptFromString:@“document.URL”];//加载的url
NSString *thisHREF = [webView stringByEvaluatingJavaScriptFromString:@“document.location.href”];//加载的url
NSString *thisProtocol = [webView stringByEvaluatingJavaScriptFromString:@“document.location.protocol”];//https协议
NSString *thisTLoc = [webView stringByEvaluatingJavaScriptFromString:@“top.location.href”];//加载的url
NSString *thisHost = [webView stringByEvaluatingJavaScriptFromString:@“location.hostname”];//域名
NSString *thisPort = [webView stringByEvaluatingJavaScriptFromString:@“document.location.protocol”];//https协议
NSString *thisTitle = [webView stringByEvaluatingJavaScriptFromString:@“document.location.port”];//端口
NSString *thisSearch = [webView stringByEvaluatingJavaScriptFromString:@“document.location.search”];//参数
NSString *thisPathname = [webView stringByEvaluatingJavaScriptFromString:@“document.location.pathname”];//路径
NSString *thisHtml = [webView stringByEvaluatingJavaScriptFromString:@“document.documentElement.innerHTML”];//html
NSString *thisBodyText = [webView stringByEvaluatingJavaScriptFromString:@“document.body.innerText”];//页面信息
五 demo链接

你可能感兴趣的:(ios随笔)