【问题标题】:C# find string and extract the hrefC#查找字符串并提取href
【发布时间】:2014-08-22 06:16:31
【问题描述】:

我有一个文件,其中包含文本。我需要搜索一个字符串并提取该行上的 href。

file.txt 是包含基本 wordpress 主页的文件

最后我想要http://example.com 链接。 我尝试了几种方法,例如

        DateTime dateTime = DateTime.UtcNow.Date;
        string stringpart = dateTime.ToString("-dd-M-yyyy");
        string finalword = "candy" + stringpart;
        List<List<string>> groups = new List<List<string>>();
        List<string> current = null;
        foreach (var line in File.ReadAllLines(@"E:/file.txt"))
        {
            if (line.Contains("-22-8-2014") && current == null)
                current = new List<string>();
            else if (line.Contains("candy") && current != null)
            {
                groups.Add(current);
                current = null;
            }
            if (current != null)
                current.Add(line);
        }

        foreach (object o in groups)
        {
            Console.WriteLine(o);
        }        
        Console.ReadLine();
    }

【问题讨论】:

标签: c# string web-services find


【解决方案1】:

要正确执行此操作,您必须解析此 html 文件。使用 CSqueryHTML Agility PackSgmlReader 之类的内容。

CSQuery 问题的解决方案:

public IEnumerable<string> ExtractLinks(string htmlFile)
{
    var page = CQ.CreateFromFile(htmlFile);
    return page.Select("a[href]").Select(tag => tag.GetAttribute("href"));
}

【讨论】:

    【解决方案2】:

    如果您决定使用 HtmlAgilityPack,这应该很容易:

    var doc = new HtmlDocument();
    //load your HTML file to HtmlDocument
    doc.Load("path_to_your_html.html");
    //select all <a> tags containing href attribute
    var links = doc.DocumentNode.SelectNodes("//a[@href]");
    foreach(HtmlNode link in links)
    {
        //print value of href attribute
        Console.WriteLine(link.GetAttributeValue("href", "");
    }
    

    【讨论】:

    • 对不起,我是 Html Agility Pack 的新手。我现在正在浏览一些文章,但很难理解。你能推荐我任何资料来获得基本的了解吗?
    • HtmlAgilityPack (HAP) 与 .NET 中的 XmlDocument 具有非常相似的类结构(方法和成员)。 XmlDocument 在 MSDN 中有完整的文档。您可以阅读该内容,并尝试在 HAP 中将 XmlDocument 简单地替换为 HtmlDocument,将 XmlNode 替换为 HtmlNode,等等。
    • 仅供参考,更正了我的样本。 SelectNodes() 方法的 XPath 字符串应该是 //a[@href] 而不是 //a[href](属性应该在开头使用 @ 引用)
    猜你喜欢
    • 2017-12-06
    • 1970-01-01
    • 2017-02-25
    • 2021-01-13
    • 1970-01-01
    • 2011-06-09
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多