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

C#中从HTML提取指定内容并显示到文本框的技术疑问

问题1:提取含viewer.php的<input>标签value属性内容并输出到文本框

推荐方案:使用HtmlAgilityPack(处理HTML更可靠)

  1. 通过NuGet安装HtmlAgilityPack包
  2. 加载HTML内容后,筛选符合条件的<input>标签
  3. 拼接结果并赋值给文本框
using HtmlAgilityPack;

// 假设htmlContent是读取到的HTML文件内容
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);

var targetValues = htmlDoc.DocumentNode.SelectNodes("//input[@value]")
    ?.Where(node => node.GetAttributeValue("value", "").Contains("viewer.php"))
    .Select(node => node.GetAttributeValue("value", ""))
    .ToList();

textBox1.Text = targetValues?.Any() == true 
    ? string.Join(Environment.NewLine, targetValues) 
    : "未找到符合条件的内容";

备选方案:正则表达式(适合简单HTML场景)

注意:复杂HTML结构下正则可能匹配不准确,需谨慎使用

using System.Text.RegularExpressions;

// 匹配带单/双引号的value属性,且内容包含viewer.php
string pattern = @"<input[^>]*value=([""'])(.*?viewer\.php.*?)\1[^>]*>";
MatchCollection matches = Regex.Matches(htmlContent, pattern, RegexOptions.IgnoreCase);

List<string> results = new List<string>();
foreach (Match match in matches)
{
    results.Add(match.Groups[2].Value);
}

textBox1.Text = string.Join(Environment.NewLine, results);

问题2:提取<img>的src属性并正确显示到文本框

第一步:修正正则匹配逻辑(避免返回数字)

如果之前返回数字,大概率是正则分组索引错误。调整FetchImgsFromSource方法:

private List<string> FetchImgsFromSource(string htmlContent)
{
    // 匹配<img>标签中带单/双引号的src属性
    string pattern = @"<img[^>]*src=([""'])(.*?)\1[^>]*>";
    MatchCollection matches = Regex.Matches(htmlContent, pattern, RegexOptions.IgnoreCase);
    
    List<string> srcList = new List<string>();
    foreach (Match match in matches)
    {
        // Groups[2]对应src的实际值,Groups[1]是匹配的引号
        string src = match.Groups[2].Value.Trim();
        if (!string.IsNullOrEmpty(src))
        {
            srcList.Add(src);
        }
    }
    return srcList;
}

第二步:将结果显示到文本框

调用方法后拼接结果赋值:

List<string> imgSrcs = FetchImgsFromSource(htmlContent);
textBox2.Text = imgSrcs.Any() 
    ? string.Join(Environment.NewLine, imgSrcs) 
    : "未找到图片链接";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:33:32