在 C# 中获取两个字符串 (HTML) 之间的文本
Get Text Between Two Strings (HTML) in C#
我正在尝试解析网站的 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 "
城市和地址有空格不知道怎么避开
Trim 字符串和不必要的空格将消失:
fullName = fullName.Trim ();
fullAddress = fullAddress.Trim ();
city = city.Trim ();
我正在尝试解析网站的 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 "
城市和地址有空格不知道怎么避开
Trim 字符串和不必要的空格将消失:
fullName = fullName.Trim ();
fullAddress = fullAddress.Trim ();
city = city.Trim ();