iOS開發(fā)中經(jīng)常需要與webView進(jìn)行一些交互操作镰官,比如獲取網(wǎng)頁上面的title,Image李茫,content等等规辱。
1.獲取網(wǎng)頁的標(biāo)題
1 )UIWebView獲取title的方法
NSString *resurltContent = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
2 )WKWebView獲取title的方法
[webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSString *resurlt = [NSString stringWithFormat:@"%@",response];
NSLog(@"這是獲取到的標(biāo)題%@", resurlt);
}];
2.獲取網(wǎng)頁上的圖片
1 )UIWebView獲取Image的方法
//這里是js,主要目的實現(xiàn)對圖片url的獲取
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
//注入JS方法
[webView stringByEvaluatingJavaScriptFromString:jsGetImages];
//調(diào)用方法疚沐,獲取到了網(wǎng)頁上所有的圖片站玄,可以根據(jù)自己需要從存放圖片Url數(shù)組里面獲取
NSString *resurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
if (resurlt.length) {
NSArray *urlArr = [resurlt componentsSeparatedByString:@"+"];
NSLog(@"這是獲取到的存放圖片Url的數(shù)組%@",urlArr);
}
2 )WKWebView獲取Image的方法
//注入JS方法
[webView evaluateJavaScript:jsGetImages completionHandler:^(id _Nullable response, NSError * _Nullable error) {
}];
//調(diào)用方法,獲取到了網(wǎng)頁上所有的圖片濒旦,可以根據(jù)自己需要從存放圖片 Url數(shù)組里面獲取
[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSString *resurlt = [NSString stringWithFormat:@"%@",response];
if (resurlt.length) {
NSArray *urlArr = [resurlt componentsSeparatedByString:@"+"];
NSLog(@"這是獲取到的存放圖片Url的數(shù)組%@",urlArr);
}
}];
3.獲取網(wǎng)頁上的文章內(nèi)容
1 )UIWebView獲取文章內(nèi)容的方法
NSString *resurltContent = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerText"];
12)WKWebView獲取文章內(nèi)容的方法
[webView evaluateJavaScript:@"document.body.innerText" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSString *resurlt = [NSString stringWithFormat:@"%@",response];
NSLog(@"這是獲取到的文章內(nèi)容%@", result);
}];
4.獲取網(wǎng)頁高度
1 )UIWebView獲取網(wǎng)頁高度
CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight" ] floatValue];
1 )WKWebView獲取網(wǎng)頁高度
[webView evaluateJavaScript:@"document.body.innerText" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
CGFloat webViewHeight = [response floatValue];
NSLog(@"這是獲取的網(wǎng)頁高度%f", result);
}];