代码改变世界

网页处理

2015-04-22 20:51  南峰_ldl  阅读(126)  评论(0)    收藏  举报

1.UIWebView的使用

w3cschool-->Javascript-->htmldom-->html dom 参考手册-->dom document

JavaScript代码与网页交互

@interface ViewController ()
<UIWebViewDelegate, UITextFieldDelegate>
{
    UIWebView *_webView;
    UITextField *_urlTextField;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //使用uiwebview 显示网页
    _urlTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 3, 280, 30)];
    _urlTextField.borderStyle = UITextBorderStyleRoundedRect;
    _urlTextField.text = @"http://www.baidu.com";
    self.navigationItem.titleView = _urlTextField;
    
    //按钮
    UIBarButtonItem *browserItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(dealBrowser)];
    self.navigationItem.rightBarButtonItem = browserItem;
    
    //初始化
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    
    UIBarButtonItem *controlItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(dealControl)];
    self.navigationItem.leftBarButtonItem = controlItem;
}
-(void)dealControl
{
    //改变图片大小
    NSString *js = @"var image = document.images[0]; image.width = 50; image.height = 50";
    [_webView stringByEvaluatingJavaScriptFromString:js];
}
-(void)dealBrowser
{
    //调用loadRequest: 方法加载网页
    NSURL *url = [NSURL URLWithString:_urlTextField.text];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //执行javascript语句
    NSString *result = nil;
    result = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"%@",result);
    
}

 

2.解析HTML文件

库的配置:build settings --> header search paths

/usr/include/libxml2

libxml2.dylib

#import "TFHpple.h"

//1.获取标题
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    TFHpple *tfhpple = [[TFHpple alloc] initWithHTMLData:data];
    //上句执行完了解析就算是完成了
    
    //获取title标签
    TFHppleElement *element = [[tfhpple searchWithXPathQuery:@"/html/head/title"] firstObject];
    NSLog(@"%@,%@",element.tagName,element.text);
    
    
    //2.获取网页中所有链接
    NSArray *array = [tfhpple searchWithXPathQuery:@"//a"];
    for (TFHppleElement *e in array) {
        NSLog(@"href = %@",e.attributes[@"href"]);
    }

 

3.设计模式

设计模式:编程经验总结

kvc 作用:解析json数据的时候将字典转换成Model

kvo 作用:监控某个对象的某个属性变化

mvc 作用:相对于非mvc来说,更容易拓展和复用