如何获取UIWebView中显示的HTML页面的标题?

发布于 2024-08-21 23:28:10 字数 648 浏览 10 评论 0原文

我需要从 UIWebView 中显示的 HTML 页面中提取标题标签的内容。这样做最有力的手段是什么?

我知道我可以这样做:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

但是,只有启用了 javascript 才有效。

或者,我可以只扫描 HTML 代码的文本来查找标题,但这感觉有点麻烦,而且如果页面的作者对其代码感到奇怪的话,可能会变得脆弱。如果涉及到这一点,在 iPhone API 中处理 html 文本的最佳方法是什么?

我觉得我忘记了一些显而易见的事情。还有比这两种选择更好的方法吗?

更新:

根据这个问题的答案:UIWebView:你可以禁用Javascript吗?那里似乎无法关闭 UIWebView 中的 Javascript。因此上面的 Javascript 方法总是有效的。

I need to extract the contents of the title tag from an HTML page displayed in a UIWebView. What is the most robust means of doing so?

I know I can do:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

However, that only works if javascript is enabled.

Alternatively, I could just scan the text of the HTML code for the title but that feels a bit cumbersome and might prove fragile if the page's authors got freaky with their code. If it comes to that, what's the best method to use for processing the html text within the iPhone API?

I feel that I've forgotten something obvious. Is there a better method than these two choices?

Update:

Following from the answer to this question: UIWebView: Can You Disable Javascript? there appears to be no way to turn off Javascript in UIWebView. Therefore the Javascript method above will always work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

野味少女 2024-08-28 23:28:10

对于那些只是向下滚动寻找答案的人:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

这将始终有效,因为无法在 UIWebView 中关闭 Javascript。

For those who just scroll down to find the answer:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

This will always work as there is no way to turn off Javascript in UIWebView.

别念他 2024-08-28 23:28:10

WKWebView 有 'title' 属性,就这样做,

func webView(_ wv: WKWebView, didFinish navigation: WKNavigation!) {
    title = wv.title
}

我认为 UIWebView 现在不合适。

WKWebView has 'title' property, just do it like this,

func webView(_ wv: WKWebView, didFinish navigation: WKNavigation!) {
    title = wv.title
}

I don't think UIWebView is suitable right now.

柠檬色的秋千 2024-08-28 23:28:10

如果启用 Javascript 使用这个:-

NSString *theTitle=[webViewstringByEvaluatingJavaScriptFromString:@"document.title"];

如果禁用 Javascript 使用这个:-

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);

我在 NSMakeRange 中使用 +7 和 -7 来消除 </code> 的长度,即 7

If Javascript Enabled Use this :-

NSString *theTitle=[webViewstringByEvaluatingJavaScriptFromString:@"document.title"];

If Javascript Disabled Use this :-

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);

I Used +7 and -7 in NSMakeRange to eliminate the length of <title> i.e 7

嗫嚅 2024-08-28 23:28:10

编辑:刚刚看到你找到了答案...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 ,并对其进行子字符串化,以便我们得到介于两者之间的内容。

    //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 中发生的所有恶作剧,如果我们仅通过说 NSMakeRange(startRange.location, endRange.location) 来创建范围,我们将获得标题和 startString 的文本(即 ),因为位置是字符串的第一个字符。
因此,为了弥补这一点,我们只是添加了字符串的长度

现在请记住,此代码尚未经过测试..如果有任何问题,可能是拼写错误,或者我没有/确实添加了指针我不应该这样做。

如果标题有点奇怪并且不完全正确,请尝试使用 NSMakeRange - 我的意思是添加/减去字符串的不同长度/位置 - 任何看起来合乎逻辑的东西。

如果您有任何疑问或有任何问题,请随时询问。这是我在这个网站上的第一个答案,如果有点杂乱,很抱歉

Edit: just saw you found out the answer... sheeeiiitttt

I literally just learned this! To do this, you don't even need to have it displayed in UIWebView. (But as you are using it, you can just get the URL of the current page)

Anyways, here's the code and some (feeble) explanation:

    //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];

So we have the HTML code, now how do we get the title? Well, in every html-based doc the title is signaled by This Is the Title
So probably the easiest thing to do is to search that htmlCode string for , and for , and substring it so we get the stuff in between.

    //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

And that's really it!
So basically to explain all the shenanigans going on in the docTitle, if we made a range just by saying NSMakeRange(startRange.location, endRange.location) we would get the title AND the text of startString (which is ) because the location is by the first character of the string.
So in order to offset that, we just added the length of the string

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

云之铃。 2024-08-28 23:28:10

这是 Swift 4 版本,基于此处的答案

func webViewDidFinishLoad(_ webView: UIWebView) {
    let theTitle = webView.stringByEvaluatingJavaScript(from: "document.title")
}

Here is Swift 4 version, based on answer at here

func webViewDidFinishLoad(_ webView: UIWebView) {
    let theTitle = webView.stringByEvaluatingJavaScript(from: "document.title")
}
何时共饮酒 2024-08-28 23:28:10

到目前为止,我没有使用 webview 的经验,但是,我相信它将标题设置为页面标题,因此,我建议的一个技巧是在 webview 上使用类别并覆盖 self.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?

_失温 2024-08-28 23:28:10

如果您在代码中经常需要它,我建议您在“扩展 UIWebView”中添加一个函数,如下所示,

extension UIWebView {

    func title() -> String {
        let title: String = self.stringByEvaluatingJavaScript(from: "document.title")!
        return title
    }
}

或者最好使用 WKWebView。

不幸的是,它在 ARKit 中没有得到很好的支持。我不得不放弃WKWebView。我无法将网站加载到 webView 中。如果有人有​​此问题的解决方案 ->我有一个类似的问题,这会有很大帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文