【问题标题】:How can I store a part of a very large HTML stream?如何存储非常大的 HTML 流的一部分?
【发布时间】:2017-02-15 17:56:47
【问题描述】:

我必须得到一个网络的 HTML 代码,然后才能找到这个类:

<span class='uccResultAmount'>0,896903</span>

我已尝试使用 正则表达式。 还有Streams,我的意思是,将整个HTML 代码存储在string 中。但是,string 的代码非常大。所以这是不可能的,因为0,896903 我正在搜索的数量在string 中不存在。

有没有办法只读取 Stream 的一小部分?

部分方法:

public static string getValue()
        {
            string data = "not found";
            string urlAddress = "http://www.xe.com/es/currencyconverter/convert/?Amount=1&From=USD&To=EUR";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                data = readStream.ReadToEnd(); // the string in which I should search for the amount

                response.Close();
                readStream.Close();
            }

如果您找到更简单的方法来解决我的问题,请告诉我。

【问题讨论】:

    标签: c# html string stream substring


    【解决方案1】:

    我会使用 HtmlAgilityPack 和 Xpath

    var web = new HtmlAgilityPack.HtmlWeb();
    var doc = web.Load("http://www.xe.com/es/currencyconverter/convert/?Amount=1&From=USD&To=EUR");
    var value = doc.DocumentNode.SelectSingleNode("//span[@class='uccResultAmount']")
                   .InnerText;
    

    Linq 版本也是可能的

    var value = doc.DocumentNode.Descendants("span")
                .Where(s => s.Attributes["class"] != null && s.Attributes["class"].Value == "uccResultAmount")
                .First()
                .InnerText;
    

    Don't use this。只是为了展示

    但问题是这段 html 代码不适合单个字符串

    不正确

    string html = new WebClient().DownloadString("http://www.xe.com/es/currencyconverter/convert/?Amount=1&From=USD&To=EUR");
    var val = Regex.Match(html, @"<span[^>]+?class='uccResultAmount'>(.+?)</span>")
                   .Groups[1]
                   .Value;
    

    【讨论】:

    • 不使用 HtmlAgilityPack 可以做到这一点吗?
    • @OscarM 你需要一个工具来解析 html。你不能使用正则表达式stackoverflow.com/questions/1732348/…
    • 但是问题是这个html代码不适合单个字符串,所以我无法解析不包含我需要的子字符串的东西。
    • @OscarM 不正确。它适合一个字符串。你认为 HtmlAgilityPack 是如何处理它的......看我的编辑
    • 是的,对不起,我刚刚将字符串导出到一个文件中,整个数据都在那里。
    猜你喜欢
    • 2011-04-10
    • 2019-08-07
    • 2011-07-21
    • 2021-09-19
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多