gpt4 book ai didi

c# - 如何在不下载所有页面源的情况下获取网页标题

转载 作者:太空狗 更新时间:2023-10-29 20:51:43 24 4
gpt4 key购买 nike

我正在寻找一种方法来获取网页标题并将其存储为字符串。

然而,到目前为止我找到的所有解决方案都涉及下载页面的源代码,这对于大量网页来说并不实用。

我能看到的唯一方法是限制字符串的长度,或者它只下载一定数量的字符,或者一旦到达标签就停止,但这显然仍然很大?

谢谢

最佳答案

作为 <title>标记在 HTML 本身中,将无法下载文件以查找“只是标题”。在阅读 <title> 之前,您应该可以下载文件的一部分。标记,或 </head>标记然后停止,但您仍然需要下载(至少部分)文件。

这可以通过 HttpWebRequest 来完成/HttpWebResponse并从响应流中读取数据,直到我们读入 <title></title> block ,或 </head>标签。我添加了 </head>标记检查,因为在有效的 HTML 中,标题 block 必须出现在头部 block 内 - 因此,通过此检查,我们在任何情况下都不会解析整个文件(当然,除非没有头部 block )。

以下应该能够完成这个任务:

string title = "";
try {
HttpWebRequest request = (HttpWebRequest.Create(url) as HttpWebRequest);
HttpWebResponse response = (request.GetResponse() as HttpWebResponse);

using (Stream stream = response.GetResponseStream()) {
// compiled regex to check for <title></title> block
Regex titleCheck = new Regex(@"<title>\s*(.+?)\s*</title>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
int bytesToRead = 8092;
byte[] buffer = new byte[bytesToRead];
string contents = "";
int length = 0;
while ((length = stream.Read(buffer, 0, bytesToRead)) > 0) {
// convert the byte-array to a string and add it to the rest of the
// contents that have been downloaded so far
contents += Encoding.UTF8.GetString(buffer, 0, length);

Match m = titleCheck.Match(contents);
if (m.Success) {
// we found a <title></title> match =]
title = m.Groups[1].Value.ToString();
break;
} else if (contents.Contains("</head>")) {
// reached end of head-block; no title found =[
break;
}
}
}
} catch (Exception e) {
Console.WriteLine(e);
}

更新:更新原始源代码示例以使用已编译的 Regex和一个 using Stream 的声明以提高效率和可维护性。

关于c# - 如何在不下载所有页面源的情况下获取网页标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11652883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com