UIWebView得到網頁內容(HTML源碼)、加載本地HTML文件


獲取網頁內容

在使用UIWebView加載一個網頁的時候,有時候須要得到此頁面的源碼,可使用UIWebView執行JS代碼來得到:css

//加載網址
let req = NSMutableURLRequest.init(URL: NSURL.init(string: "http://zhaoyabei.github.io/")!)
web.loadRequest(req)

//輸出網頁內容
let lJs = "document.documentElement.innerHTML"
let lHtml1 = web.stringByEvaluatingJavaScriptFromString(lJs)
print("\(lHtml1)")

輸出內容爲:html

<head>\n  <meta charset=\"UTF-8\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">\n\n\n\n<meta http-equiv=\"Cache-Control\" content=\"no-transform\">\n<meta http-equiv=\"Cache-Control\" content=\"no-siteapp\">\n\n\n\n\n\n\n\n\n\n\n\n\n  \n  \n  <link href=\"/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5\" rel=\"stylesheet\" type=\"text/css\">\n\n\n\n\n  \n  \n  \n  \n\n  \n    \n    \n  \n\n  \n\n  \n\n  \n\n  \n\n  \n    \n    \n    <link href=\"//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&amp;subset=latin,latin-ext\" rel=\"stylesheet\" type=\"text/css\">\n  \n\n\n\n\n\n\n<link href=\"/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0\" rel=\"stylesheet\" type=\"text/css\">\n\n<link href=\"/css/main.css?v=5.0.1\" rel=\"stylesheet\" type=\"text/css\">\n\n\n  <meta name=\"keywords\" content=\"ZhaoYaBei\">\n\n\n\n\n\n\n\n\n  <link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/favicon.ico?v=5.0.1\">\n\n\n\n\n\n\n<meta name=\"description\" content=\"Blog of development\">\n<meta property=\"og:type\" content=\"website\">\n<meta property=\"og:title\" content=\"也無風雨也無晴\">\n<meta property=\"og:url\" content=\"http://yoursite.com/index.html\">\n<meta property=\"og:site_name\" content=\"也無風雨也無晴\">...

加載本地HTML文件

加載工程中名爲「index.html」文件jquery

//得到路徑
let path = NSBundle.mainBundle().pathForResource("index", ofType: "html")
let content = try? NSString.init(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
//baseUrl
let baseUrl = NSURL.init(fileURLWithPath: NSBundle.mainBundle().bundlePath)
//加載
web.loadHTMLString(content as! String, baseURL: baseUrl )
相關文章
相關標籤/搜索