How can I get the HTML
source code of a UIWebView
and store it in NSString
?
Asked
Active
Viewed 5.3k times
25

Jagat Dave
- 1,643
- 3
- 23
- 30

Wasim A.
- 9,660
- 22
- 90
- 120
-
what actually you want to ask? – Swastik Mar 02 '11 at 12:12
-
i have open google.com in my uiwebview and now i want to get html source code of website opened in uiwebview ... basically i required value of action in – Wasim A. Mar 02 '11 at 12:15
-
http://stackoverflow.com/questions/992348/reading-html-content-from-a-uiwebview – rptwsthi Jun 22 '13 at 06:24
-
there is a difference between two questions, my question was how to read HTML from UIWebView where HTML is preloaded where as other question is reading HTML before loaded into WebView – Wasim A. Jun 23 '13 at 15:36
2 Answers
94
If you want the source code of an already loaded webview, you can get it like this:
NSString *yourHTMLSourceCodeString = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
Update: method above works most of the time. But I recently was in a situation where I needed all the code source, not just the body.
Here is a better way:
NSString *yourHTMLSourceCodeString = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
(It won't reload the webview).

Guillaume
- 21,685
- 6
- 63
- 95
3
I am not sure that what exactly you need..........but as per your last comment you will get that html data from google like this...
NSData *companyData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
NSString *responseString = [[NSString alloc] initWithData:companyData encoding:NSUTF8StringEncoding];
self.yourTextView.text = responseString; // response string contains that data
[companyData release];
Good Luck!

Sudhanshu
- 3,950
- 1
- 19
- 18
-
2I suppose the problem here is that using `dataWithContentsOfURL:` requires the web page data to be retrieved again, rather than being extracted from the already loaded UIWebView – Apr 23 '12 at 09:17