从 UIWebView 读取 HTML 内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/992348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:54:09  来源:igfitidea点击:

Reading HTML content from a UIWebView

htmliphoneuiwebview

提问by Fuzzy Purple Monkey

Is it possible to read the raw HTML content of a web page that has been loaded into a UIWebView?

是否可以读取已加载到UIWebView.

If not, is there another way to pull raw HTML content from a web page in the iPhone SDK (such as an equivalent of the .NET WebClient::openRead)?

如果没有,是否有另一种方法可以从 iPhone SDK 中的网页中提取原始 HTML 内容(例如相当于 .NET WebClient::openRead)?

回答by Tim

The second question is actually easier to answer. Look at the stringWithContentsOfURL:encoding:error:method of NSString - it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:

第二个问题其实更容易回答。看看stringWithContentsOfURL:encoding:error:NSString的方法——它允许你将 URL 作为 NSURL 的一个实例传入(可以很容易地从 NSString 实例化)并返回一个包含该 URL 页面完整内容的字符串。例如:

NSString *googleString = @"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL 
                                                encoding:NSASCIIStringEncoding
                                                   error:&error];

After running this code, googlePagewill contain the HTML for www.google.com, and errorwill contain any errors encountered in the fetch. (You should check the contents of errorafter the fetch.)

运行此代码后,googlePage将包含 www.google.com 的 HTML,error并将包含获取中遇到的任何错误。(您应该检查error获取后的内容。)

Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You'll have to pull the requestfrom the view, then do the fetch as before:

走另一条路(从 UIWebView)有点棘手,但基本上是相同的概念。您必须从视图中提取请求,然后像以前一样进行提取:

NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL 
                                          encoding:NSASCIIStringEncoding
                                             error:&error];

EDIT:Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its stringByEvaluatingJavascriptFromString:method, as such:

编辑:然而,这两种方法都会影响性能,因为它们两次执行请求。您可以通过使用其stringByEvaluatingJavascriptFromString:方法从当前加载的 UIWebView 中获取内容来解决此问题,如下所示:

NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: 
                                         @"document.body.innerHTML"];

This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.

这将使用文档对象模型获取视图的当前 HTML 内容,解析 JavaScript,然后将其作为 HTML 的 NSString* 提供给您。

Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let's say you take the second example above, where you have NSString *pageas the result of a call to stringWithContentsOfURL:encoding:error:. You can then push that string into the web view using loadHTMLString:baseURL:, assuming you also held on to the NSURL you requested:

另一种方法是首先以编程方式执行您的请求,然后从您请求的内容中加载 UIWebView。假设您采用上面的第二个示例,其中NSString *page调用stringWithContentsOfURL:encoding:error:. 然后,您可以使用 将该字符串推送到 Web 视图中loadHTMLString:baseURL:,假设您还保留了您请求的 NSURL:

[yourWebView loadHTMLString:page baseURL:requestURL];

I'm not sure, however, if this will run JavaScript found in the page you load (the method name, loadHTMLString, is somewhat ambiguous, and the docs don't say much about it).

但是,我不确定这是否会运行在您加载的页面中找到的 JavaScript(方法名称 ,loadHTMLString有点含糊不清,而且文档对此没有太多说明)。

For more info:

欲了解更多信息:

回答by Ben Gottlieb

if you want to extract the contents of an already-loaded UIWebView, -stringByEvaluatingJavaScriptFromString. For example:

如果要提取已加载的 UIWebView 的内容,请使用 -stringByEvaluatingJavaScriptFromString。例如:

NSString  *html = [webView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];

回答by tuoxie007

To get the whole HTML raw data (with <head>and <body>):

要获取整个 HTML 原始数据(使用<head><body>):

NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];

回答by Pmatt

Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

请注意,NSString stringWithContentsOfURL 将报告与发出相同请求的 UIWebView 完全不同的用户代理字符串。因此,如果您的服务器知道用户代理,并且根据请求者发回不同的 html,则您可能无法通过这种方式获得正确的结果。

Also note that the @"document.body.innerHTML"mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML"you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

还要注意,@"document.body.innerHTML"上面提到的只会显示 body 标签中的内容。如果您使用,@"document.all[0].innerHTML"您将获得头部和身体。这仍然不是 UIWebView 的完整内容,因为它不会取回 !doctype 或 html 标签,但它更接近。

回答by Agni

To read:-

阅读:-

NSString *html = [myWebView stringByEvaluatingJavaScriptFromString: @"document.getElementById('your div id').textContent"];
NSLog(html);    

To modify:-

修改:-

html = [myWebView stringByEvaluatingJavaScriptFromString: @"document.getElementById('your div id').textContent=''"];

回答by Mc.Lover

In Swift v3:

在 Swift v3 中:

let doc = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")

回答by Nathan

I use a swift extension like this:

我使用这样的快速扩展:

extension UIWebView {
    var htmlContent:String? {
        return self.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
    }

}

回答by yoAlex5

One more example

再举一个例子

let content = uiWebView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")

get HTML from WKWebView
put HTML into UIWebView
put HTML into WKWebView

从 WKWebView 获取 HTML
将 HTML 放入 UIWebView
将 HTML 放入 WKWebView

回答by Matthew Ferguson

(Xcode 5 iOS 7) Universal App example for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)

(Xcode 5 iOS 7) 适用于 iOS 7 和 Xcode 5 的通用应用程序示例。它是一个开源项目/示例,位于此处:链接到 SimpleWebView(项目邮编和源代码示例)

回答by schumyxp

you should try this:

你应该试试这个:

document.documentElement.outerHTML