【问题标题】:Get Text Between Two Strings (HTML) in C#在 C# 中获取两个字符串 (HTML) 之间的文本
【发布时间】:2015-08-11 03:51:41
【问题描述】:

我正在尝试解析网站的 HTML,然后在两个字符串之间获取文本。

我写了一个小函数来获取两个字符串之间的文本。

public string getBetween(string strSource, string strStart, string strEnd)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }
    else
    {
        return string.Empty;
    }
}

我将 HTML 存储在一个名为“html”的字符串中。这是我要解析的 HTML 的一部分:

<div class="info">
                                    <div class="content">
                                        <div class="address">
                                        <h3>Andrew V. Kenny</h3>
                                        <div class="adr">
                                        67 Romines Mill Road<br/>Dallas, TX 75204                                        </div>
                                    </div>

<p>Curious what <strong>Andrew</strong> means? <a href="http://www.babysfirstdomain.com/meaning/boy/andrew">Click here to find out!</a></p>

所以,我是这样使用我的函数的。

    string m2 = getBetween(html, "<div class=\"address\">", "<p>Curious what");
    string fullName = getBetween(m2, "<h3>", "</h3>");
    string fullAddress = getBetween(m2, "<div class=\"adr\">", "<br/>");
    string city = getBetween(m2, "<br/>", "</div>");

全名的输出工作正常,但其他人出于某种原因在其中有额外的空格。我尝试了各种方法来避免它们(例如从源中完全复制空格并将它们添加到我的函数中)但它不起作用。

我得到这样的输出:

fullName = "Andrew V. Kenny"
fullAddress = "                                            67 Romines Mill Road"
city = "Dallas, TX 75204                                        "

城市和地址中有一些我不知道如何避免的空间。

【问题讨论】:

  • 您的输出是否包含所有空格..?
  • @Ben 是的,输出 (HTML) 包含空格。我曾尝试用空格复制确切的短语,但在解析时它不起作用。我也发布了一个示例 HTML 在我的帖子中的外观。

标签: c# html-parsing


【解决方案1】:

修剪字符串,多余的空格就会消失:

fullName = fullName.Trim ();
fullAddress = fullAddress.Trim ();
city = city.Trim ();

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    相关资源
    最近更新 更多