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链接

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值