UIWebView에 표시되는 HTML 페이지의 제목을 얻는 방법?
UIWebView에 표시된 HTML 페이지에서 제목 태그의 내용을 추출해야합니다. 그렇게하는 가장 강력한 방법은 무엇입니까?
나는 내가 할 수 있다는 것을 안다.
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
그러나 자바 스크립트가 활성화 된 경우에만 작동합니다.
또는 제목의 HTML 코드 텍스트를 스캔 할 수는 있지만 약간 번거롭고 페이지 작성자가 코드에 열광적 인 경우 깨지기 쉽습니다. 그렇다면 iPhone API 내에서 html 텍스트를 처리하는 데 가장 좋은 방법은 무엇입니까?
나는 분명한 것을 잊었다 고 생각합니다. 이 두 가지 선택보다 더 나은 방법이 있습니까?
최신 정보:
이 질문에 대한 답변에서 다음과 같습니다. UIWebView : Javascript를 비활성화 할 수 있습니까? UIWebView에서 Javascript를 끄는 방법이없는 것 같습니다. 따라서 위의 자바 스크립트 방법이 항상 작동합니다.
아래로 스크롤하여 답을 찾는 사람들을 위해 :
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
UIWebView에서 Javascript를 끄는 방법이 없으므로 항상 작동합니다.
자바 스크립트가 활성화 된 경우 다음을 사용하십시오.
NSString *theTitle=[webViewstringByEvaluatingJavaScriptFromString:@"document.title"];
자바 스크립트가 비활성화 된 경우 다음을 사용하십시오.
NSString * htmlCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.appcoda.com"] encoding:NSASCIIStringEncoding error:nil];
NSString * start = @"<title>";
NSRange range1 = [htmlCode rangeOfString:start];
NSString * end = @"</title>";
NSRange range2 = [htmlCode rangeOfString:end];
NSString * subString = [htmlCode substringWithRange:NSMakeRange(range1.location + 7, range2.location - range1.location - 7)];
NSLog(@"substring is %@",subString);
나는 <title>7 의 길이를 제거하기 위해 NSMakeRange에서 +7과 -7을 사용했습니다.
WKWebView 'title'속성이 있습니다.
func webView(_ wv: WKWebView, didFinish navigation: WKNavigation!) {
title = wv.title
}
UIWebView지금은 적당 하지 않다고 생각 합니다.
편집 : 당신이 답을 찾은 것을 보았습니다 ... sheeeiiitttt
나는 문자 그대로 이것을 배웠다! 이를 위해 UIWebView에 표시하지 않아도됩니다. (하지만 사용하면서 현재 페이지의 URL을 얻을 수 있습니다)
어쨌든, 여기에 코드와 (약한) 설명이 있습니다 :
//create a URL which for the site you want to get the info from.. just replace google with whatever you want
NSURL *currentURL = [NSURL URLWithString:@"http://www.google.com"];
//for any exceptions/errors
NSError *error;
//converts the url html to a string
NSString *htmlCode = [NSString stringWithContentsOfURL:currentURL encoding:NSASCIIStringEncoding error:&error];
HTML 코드가 있는데 제목을 어떻게 얻습니까? 글쎄, 모든 HTML 기반 문서에서 제목은 This Is the Title로 표시됩니다. 아마도 가장 쉬운 방법은 htmlCode 문자열을 for 및 for 및 하위 문자열로 검색하여 그 사이에 물건을 가져 오는 것입니다.
//so let's create two strings that are our starting and ending signs
NSString *startPoint = @"<title>";
NSString *endPoint = @"</title>";
//now in substringing in obj-c they're mostly based off of ranges, so we need to make some ranges
NSRange startRange = [htmlCode rangeOfString:startPoint];
NSRange endRange = [htmlCode rangeOfString:endPoint];
//so what this is doing is it is finding the location in the html code and turning it
//into two ints: the location and the length of the string
//once we have this, we can do the substringing!
//so just for easiness, let's make another string to have the title in
NSString *docTitle = [htmlString substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location)];
NSLog(@"%@", docTitle);
//just to print it out and see it's right
그게 다야! 따라서 기본적으로 docTitle에서 진행되는 모든 shenanigans를 설명하기 위해 NSMakeRange (startRange.location, endRange.location)라고 말하면 범위를 만들면 제목과 startString의 텍스트를 얻습니다. 문자열의 첫 문자 이를 오프셋하기 위해 문자열 길이를 추가했습니다.
Now keep in mind this code is not tested.. if there are any problems it might be a spelling error, or that I didn't/did add a pointer when i wasn't supposed to.
If the title is a little weird and not completely right, try messing around with the NSMakeRange-- I mean like add/subtract different lengths/locations of the strings --- anything that seems logical.
If you have any questions or there are any problems, feel free to ask. This my first answer on this website so sorry if it's a little disorganized
Here is Swift 4 version, based on answer at here
func webViewDidFinishLoad(_ webView: UIWebView) {
let theTitle = webView.stringByEvaluatingJavaScript(from: "document.title")
}
I dońt have experience with webviews so far but, i believe it sets it´s title to the page title, so, a trick I suggest is to use a category on webview and overwrite the setter for self.title so you add a message to one of you object or modify some property to get the title.
Could you try and tell me if it works?
If you need it frequently in your code, i suggest you to add a func into "extension UIWebView" like this
extension UIWebView {
func title() -> String{
let title: String = self.stringByEvaluatingJavaScript(from: "document.title")!
return title
}
alternatively its better to use WKWebView.
Unfortunately, its not well supported in ARKit. I had to give up on WKWebView. I couldnt load the website into the webView. If someone has a solution to this issue here -> i have a simlar problem, it would help greatly.
'IT' 카테고리의 다른 글
| MVVM을 사용하여 wpf의 대화 상자에 대한 좋은 습관 또는 나쁜 습관? (0) | 2020.06.18 |
|---|---|
| Java 웹 애플리케이션에 사용하는 아키텍처를 설명 하시겠습니까? (0) | 2020.06.18 |
| IFRAME로드가 완료되면 Javascript 콜백? (0) | 2020.06.18 |
| Chrome에서 개발자 모드 확장 프로그램 팝업 사용 중지 (0) | 2020.06.18 |
| 스택 샘플링을 넘어서 : C ++ 프로파일 러 (0) | 2020.06.18 |