You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何从网页内容中提取包含指定关键词的整行或整段内容

实现方案

方案1:提取包含关键词的整行内容

你可以逐行读取响应流,判断每行是否包含目标关键词,匹配到就存入display变量,相比一次性读取全量内容再拆分,内存效率更高,适合大体积网页的场景。
修改后的完整代码如下:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=" + "msg");
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();

// 初始化display为空
display = string.Empty;

using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
    string line;
    // 逐行读取响应内容
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("find"))
        {
            // 匹配到关键词就把当前行赋值给display
            display = line;
            // 如果需要匹配所有符合条件的行,就改成 display += line + Environment.NewLine; 不需要的话直接break退出循环即可
            break;
        }
    }
}

如果你需要保留原来一次性读取全量内容的逻辑,也可以对读取到的pageContent按换行拆分后遍历匹配,代码如下:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=" + "msg");
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
string pageContent = string.Empty;
display = string.Empty;

using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
    pageContent = sr.ReadToEnd();
}

// 按换行符拆分所有行
var allLines = pageContent.Split(new[] { Environment.NewLine, "\n", "\r" }, StringSplitOptions.None);
foreach (var line in allLines)
{
    if (line.Contains("find"))
    {
        display = line;
        // 匹配多行行的话去掉break,累加内容即可
        break;
    }
}

方案2:提取包含关键词的整段网页内容

如果是要匹配网页中被<p>标签包裹的整段内容,可以用正则匹配实现:

using System.Text.RegularExpressions;

// 前面请求网页的逻辑不变
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=" + "msg");
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
string pageContent = string.Empty;
display = string.Empty;

using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
    pageContent = sr.ReadToEnd();
}

// 正则匹配包含find的p标签内容
Match match = Regex.Match(pageContent, @"<p[^>]*>.*?find.*?</p>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (match.Success)
{
    display = match.Value;
    // 如果需要去掉p标签只留文本,可以再加一步:display = Regex.Replace(display, @"<[^>]+>", "").Trim();
}

补充说明

  • 如果需要匹配所有符合条件的行/段落,把break去掉,改用字符串累加或者用List<string>存储所有匹配结果即可
  • 如果需要忽略关键词的大小写,可以把Contains("find")改成IndexOf("find", StringComparison.OrdinalIgnoreCase) >= 0

内容的提问来源于stack exchange,提问作者yashash gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:48:04