iOS獲取網頁上資料(圖片、文字、視訊)
阿新 • • 發佈:2019-01-09
獲取網頁上所有圖片、獲取所有html、獲取網頁title、獲取網頁內容文字。。。
.h 檔案 程式碼:
//網頁
//NSString *strPath = [NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@&cl=3",theWord];
//視訊
//NSString *strPath = [NSString stringWithFormat:@"http://www.itinge.com/music/16241.mp4"];
//圖片
NSString *strPath = [NSString stringWithFormat:@"http://image.baidu.com/search/index?tn=baiduimage&istype=2&ie=utf-8&word=%@" ,theWord];
strPath = [strPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
.m 檔案 程式碼:
@interface ViewController ()<UISearchBarDelegate , UIWebViewDelegate,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic ) IBOutlet UIWebView *webview;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_searchBar.delegate = self;
_webview.delegate = self;
[self addTapOnWebView];
}
-(void)addTapOnWebView{
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[_webview addGestureRecognizer:singleTap];
singleTap.delegate = self;
singleTap.cancelsTouchesInView = NO;
}
#pragma mark- TapGestureRecognizer
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
//被點選位置對應連結
-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
CGPoint pt = [sender locationInView:_webview];
NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];
NSString *urlToSave = [_webview stringByEvaluatingJavaScriptFromString:imgURL];
NSLog(@"image url=%@", urlToSave);
NSString * JsToGetHTMLSource = @"top.location.href";
NSString * pageSource = [_webview stringByEvaluatingJavaScriptFromString:JsToGetHTMLSource];
NSLog(@"\n\n__url=%@", pageSource);
if (urlToSave.length > 4) {
NSString *substr = [urlToSave substringFromIndex:urlToSave.length-3];
if([substr isEqualToString:@"jpg"] || [substr isEqualToString:@"png"]){
[self showImageURL:urlToSave point:pt];
}
}
}
//呈現圖片,HTML是否適配解析度將影響點選資源與獲取到得資源是否一致
-(void)showImageURL:(NSString *)url point:(CGPoint)point
{
UIImageView *showView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
showView.center = point;
CGPoint newPoint = self.view.center;
showView.center = newPoint;
showView.backgroundColor = [UIColor blackColor];
showView.alpha = 1;
showView.userInteractionEnabled = YES;
[self.view addSubview:showView];
[showView setContentMode:UIViewContentModeScaleAspectFit];
[showView showImageFromURL:url placeHolder:nil CompletionBlock:nil];
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleViewTap:)];
[showView addGestureRecognizer:singleTap];
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
//移除圖片檢視檢視
-(void)handleSingleViewTap:(UITapGestureRecognizer *)sender
{
for (id obj in self.view.subviews) {
if ([obj isKindOfClass:[UIImageView class]]) {
[obj removeFromSuperview];
}
}
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
*JavaScript獲取網頁資訊總結
獲取所有html:NSString *lJs = @"document.documentElement.innerHTML";
獲取網頁title:NSString *lJs2 = @"document.title";
UIWebView *lWebView = [self getCurrentWebView];
NSString *lHtml1 = [lWebView stringByEvaluatingJavaScriptFromString:lJs];
NSString *lHtml2 = [lWebView stringByEvaluatingJavaScriptFromString:lJs2];
JavaScript獲取網頁資訊總結
JavaScript獲取當前頁面URL、title等
thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
thisTLoc = top.location.href;
thisPLoc = parent.document.location;
thisTHost = top.location.hostname;
thisHost = location.hostname;
thisTitle = document.title;
thisProtocol = document.location.protocol;
thisPort = document.location.port;
thisHash = document.location.hash;
thisSearch = document.location.search;
thisPathname = document.location.pathname;
thisHtml = document.documentElement.innerHTML;
thisBodyText = document.documentElement.innerText;//獲取網頁內容文字
thisBodyText = document.body.innerText;//獲取網頁內容文字 怎麼和上一個一樣?有知道的請解釋
*/
//獲取
- (IBAction)receiveAction:(id)sender {
/*1視訊*/
/*
//獲取網頁中所有視訊
NSString *getVideoTitle = [_webview getVideoTitle];
NSLog(@"\n\n 視訊名稱 : %@",getVideoTitle);
double getVideoDuration = [_webview getVideoDuration];
NSLog(@"\n\n 視訊總時間 : %f",getVideoDuration);
double getVideoCurrentTime = [_webview getVideoCurrentTime];
NSLog(@"\n\n 視訊當前時間 : %f",getVideoCurrentTime);
*/
/*2網頁*/
/*
//獲取網頁中所有圖片
NSString *imageUrls = [_webview stringByEvaluatingJavaScriptFromString:@"var str=new Array();""$('img').each(function(){str.push($(this).attr('src'));});"
"str.join(',');"];
NSLog(@"\n\n 所有圖片 : %@",imageUrls);
//獲取所有html
NSString *lJs = @"document.documentElement.innerHTML";
NSString *lHtml1 = [_webview stringByEvaluatingJavaScriptFromString:lJs];
//NSLog(@"1.%@",lHtml1);
//獲取網頁title:
NSString *lJs2 = @"document.title";
NSString *lHtml2 = [_webview stringByEvaluatingJavaScriptFromString:lJs2];
NSLog(@"2.%@",lHtml2);
//thisURL = document.URL
NSString *lJs3 = @"document.URL";
NSString *lHtml3 = [_webview stringByEvaluatingJavaScriptFromString:lJs3];
NSLog(@"3.%@",lHtml3);
//獲取網頁內容文字
NSString *lJs4 = @"document.documentElement.innerText";
NSString *lHtml4 = [_webview stringByEvaluatingJavaScriptFromString:lJs4];
NSLog(@"4.%@",lHtml4);
//獲取網頁內容文字
NSString *lJs5 = @"document.body.innerText";
NSString *lHtml5 = [_webview stringByEvaluatingJavaScriptFromString:lJs5];
NSLog(@"5.%@",lHtml5);
*/
/*3圖片*/
/**/
//獲取所有html
NSString *innerHTML = @"document.documentElement.innerHTML";
NSString *innerHTMLString = [_webview stringByEvaluatingJavaScriptFromString:innerHTML];
//檢索圖片
if(![innerHTMLString isEqualToString:@"<head></head><body></body>"]){
[self searchPictureFromHTML:innerHTMLString];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"請先搜尋關鍵字" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil nil];
[alert show];
}
}
//檢索圖片
-(void)searchPictureFromHTML:(NSString *)theHTML{
//"http://img0.bdstatic.com/img/image/shouye/qwscmeb02.jpg”
NSMutableArray *picMutableArr = [[NSMutableArray alloc] init];
NSMutableArray *picHttpArr = [[theHTML componentsSeparatedByString:@"http://"] mutableCopy];
for (int i = 0; i < picHttpArr.count ; i ++) {
NSString *tempStr = [picHttpArr objectAtIndex:i];
NSArray *tempArr = [tempStr componentsSeparatedByString:@".jpg"];
NSString *firstStr = [tempArr firstObject];
//判斷字串是否為圖片
if([self judgeStringIsPicture:firstStr]){
if([self judgeStringIsNull:firstStr]){
NSString *picUrl = [NSString stringWithFormat:@"http://%@.jpg",firstStr];
[picMutableArr addObject:picUrl];
}
}else{
}
}
//清除重複圖片
picMutableArr = [self cleanRepeatPicture:picMutableArr];
//展示獲取圖片
PictureViewController *picVc = [[PictureViewController alloc] initWithNibName:@"PictureViewController" bundle:nil];
picVc.valueArr = picMutableArr;
[self.navigationController pushViewController:picVc animated:YES];
}
//判斷字串是否為圖片連結
-(BOOL)judgeStringIsPicture:(NSString *)string{
BOOL result = YES;
NSMutableArray *mutable = [[NSMutableArray alloc] initWithObjects:@"<",@">",@"{",@"}",@"[",@"]",@"(",@")",@"|",@"||",@"$",@"?",@";", nil nil];
if(string != nil && string.length > 0){
for (int i = 0; i < string.length; i ++) {
NSString *subStr = [string substringWithRange:NSMakeRange(i, 1)];
for (int j = 0; j < mutable.count ; j ++) {
NSString *markStr = [mutable objectAtIndex:j];
if([subStr isEqualToString:markStr]){
result = NO;
}
}
}
}
return result;
}
//清除重複圖片
-(NSMutableArray *)cleanRepeatPicture:(NSMutableArray *)picarr{
NSMutableArray *tempArr = [[NSMutableArray alloc] init];
for (int i = picarr.count-1 ; i >= 0 ; i --) {
NSString *tempStr = [picarr objectAtIndex:i];
NSArray *oneArr = [tempStr componentsSeparatedByString:@"&fm"];
if(tempArr.count == 0){
[tempArr insertObject:tempStr atIndex:0];
}else{
BOOL result = YES;
for (int j = 0 ; j < tempArr.count ; j ++) {
NSString *jstr = [tempArr objectAtIndex:j];
if([jstr isEqualToString:tempStr]){
result = NO;
}else{
if(oneArr.count > 1){
NSArray *twoArr = [jstr componentsSeparatedByString:@"&fm"];
if([[oneArr firstObject] isEqualToString:[twoArr firstObject]]){
result = NO;
}
}
}
}
if(result){
[tempArr insertObject:tempStr atIndex:0];
}
}
}
return tempArr;
}
//HTML
-(void)detailsWithUrl:(NSString *)urlStr{
NSURL *url =[NSURL URLWithString:urlStr];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[_webview loadRequest:request];
[_webview setScalesPageToFit:YES];
//隱藏滾動條
_webview.backgroundColor=[UIColor clearColor];
_webview.opaque = NO;
for (UIView *aView in [_webview subviews]){
[aView setBackgroundColor:[UIColor clearColor]];
if ([aView isKindOfClass:[UIScrollView class]]){
UIScrollView *tempSV = (UIScrollView *)aView;
tempSV.tag = 1321;
[tempSV setShowsHorizontalScrollIndicator:NO]; //右側的滾動條 (水平的類似)
[tempSV setShowsVerticalScrollIndicator:NO];
[tempSV setBounces:NO];
[tempSV setContentSize:CGSizeMake(1,tempSV.contentSize.height )];
for (UIView *shadowView in tempSV.subviews){
if ([shadowView isKindOfClass:[UIImageView class]]){
shadowView.hidden = YES; //上下滾動出邊界時的黑色的圖片 也就是拖拽後的上下陰影
}
}
}
}
}
//判斷字串不全為空
-(BOOL)judgeStringIsNull:(NSString *)string{
BOOL result = NO;
if(string != nil && string.length > 0){
for (int i = 0; i < string.length; i ++) {
NSString *subStr = [string substringWithRange:NSMakeRange(i, 1)];
if(![subStr isEqualToString:@" "] && ![subStr isEqualToString:@""]){
result = YES;
}
}
}
return result;
}
#pragma mark UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
if([self judgeStringIsNull:searchBar.text]){
//搜尋介面
NSString *urlStr = [NetPortShared baiduSearchDelegate:self andTag:33333 andWord:_searchBar.text];
[self detailsWithUrl:urlStr];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"請輸入關鍵字" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil nil];
[alert show];
}
}
@end
示意圖:
文/作者:楓志應明