iOS获取网页上数据(图片、文字、视频)

转载 2016年08月30日 17:59:07

Demo地址:http://download.csdn.net/detail/u012881779/8831835

获取网页上所有图片、获取所有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

示意图:
这里写图片描述
这里写图片描述
文/作者:枫志应明

c博客地址:http://blog.csdn.net/wsyx768/article/details/46618125

教你利用一款小软件轻松下载iPhone网页上的视频

苹果手机有个痛点,就是不支持文件管理。对于那些需要在移动端处理文档或者说整理文件的朋友来说,没有文件管理这个功能绝对让人抓狂,好在作为良心企业的Readdle,为我们开发了Documents,并且免费...
  • u011884440
  • u011884440
  • 2017年06月17日 09:21
  • 16016

iOS-获取UIWebView或者WKWebView页面的视频连接

说明 不论使用的是UIWebView还是WKWebView,控件在加载有视频的网页时,我们想抓取网页上的视频链接,用来干其他的事,这里我演示抓取视频链接用自己自定义的视频播放器来播放。 UIWebVi...
  • u014220518
  • u014220518
  • 2017年03月15日 11:00
  • 3284

iOS获取本地视频和网络URL视频的缩略图方法

首先大家先添加AVFoundation和CoreMedia.framework两个框架 第一种本地视频获取缩略图 NSString *path = @"www.51ios.net/本地路径" ...
  • ANDY_GUO_wei
  • ANDY_GUO_wei
  • 2016年03月30日 16:44
  • 6812

IOS应用抓取HTML网页数据

举例抓取hao123上的搞笑图片及Gif动画的网址为例。 1.目标网址:http://www.hao123.com/gaoxiao?pn=1 2.获取HTML数据。方法如下:NSString *h...
  • zm53373581
  • zm53373581
  • 2015年09月10日 14:20
  • 10460

使用URL读取网页的内容

我们使用stringWithContentsOfURL这个NSString的类方法来读取: int main(int argc, const char * argv[]) { NSURL *u...
  • yi_zz32
  • yi_zz32
  • 2015年09月27日 21:07
  • 4769

5种方法告诉你怎么从图片中提取文字

说到图片提取文字,有时候我们还真的会遇到这样的情况。今天我跟大家分享提取文字的好方法,分为手机端、PC端和在线端,大伙儿自个儿看着用吧。 一、手机端 1、QQ 有没有很意外?现在使用...
  • qq_40427481
  • qq_40427481
  • 2017年10月17日 17:34
  • 16576

IOS 获取视频图片的

获取视频图片的 +(UIImage *)getImage:(NSString *)videoURL {     //视频地址     NSURL...
  • yangchen9931
  • yangchen9931
  • 2015年09月22日 23:21
  • 260

抓取网站中的视频

最近想从别人家的网站宣传片上提取一些素材,借鉴一下。之前也没有弄过,但是我的思路就是从网页的缓存中查找播放完后缓存的视频。然后失败了。然后又想到了网页打开源代码,然后查找到网页源代码饮用的视频的路径,...
  • Lu_Ca
  • Lu_Ca
  • 2017年09月15日 10:59
  • 247

[IOS]获取网页上数据(图片、文字、视频)

[IOS]获取网页上数据(图片、文字、视频) Demo地址:http://download.csdn.net/detail/u012881779/8831835 获取网页上所有图片...
  • u012881779
  • u012881779
  • 2015年06月24日 10:01
  • 1942

iOS在图片上添加文字或图片

Objective-C在图片上添加文字或者图片
  • glt_code
  • glt_code
  • 2016年09月30日 15:58
  • 1818
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:iOS获取网页上数据(图片、文字、视频)
举报原因:
原因补充:

(最多只允许输入30个字)