2012-10-03 35 views
-1

特定單詞串後我有一個字符串,這個網站:獲得在C#

<div class="cnt_listas"><ol id="listagem1" class="cols_2"> 
<li><a href="/laura-pausini/73280/">16/5/74</a></li> 
<li><a href="/laura-pausini/73280/traducao.html">16/5/74</a></li> 
</div> 

我需要得到<ol id="listagem1" class="cols_2"></div>之間的所有文本。 此字符串中的文字可能與此不同,它是網站的結果。 我怎樣才能得到這部分的文字?

在這種情況下,我需要將文本:

<li><a href="/laura-pausini/73280/">16/5/74</a></li> 
<li><a href="/laura-pausini/73280/traducao.html">16/5/74</a></li> 
+3

之間是什麼?此外,你到目前爲止嘗試過什麼? –

+0

在HTML解析器上搜索-1 – Paparazzi

+0

您是否考慮過正確的HTML解析庫?像HtmlAgilityPack一樣? –

回答

-1

我不明白究竟你在說什麼......也許這樣的:

string specificWord = stringWhtml.Substring(stringWhtml.IndexOf("cols_2") + 8, stringWhtml.IndexOf("</div>")); 
0

這個怎麼樣代碼,我發現幾周前在Stackoverflow上需要相同的算法嗎?

private IEnumerable<string> GetSubStrings(string input, string start, string end) 
{ 
    Regex r = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end)); 
    MatchCollection matches = r.Matches(input); 
    foreach (Match match in matches) 
     yield return match.Groups[1].Value; 
} 

編輯:This是此代碼的來源。

編輯2:要對我的答案的一個評論,請看看this

+1

Eeewwww正則表達式的HTML .. –

+1

@SimonWhitehead:我給你留下了我的答案。 –

+0

以及如何處理返回的值? IEnumerable 我可以將它轉換爲字符串嗎? –

0

不是真的來解析HTML的最佳方式,但這裏的擴展方法,將在道路上的琴絃一般工作,你都在問:

public static string Between(this string source, string start, string end) 
{ 
    // Find the first occurence of the start string 
    var i = source.IndexOf(start); 
    if (i < 0) 
     return string.Empty; 

    // Advance past the start string 
    i += start.Length; 

    // Find the next occurence of the end string 
    var j = source.IndexOf(end, i); 
    if (j < 0) 
     return string.Empty; 

    // Return the string found between the positions 
    return source.Substring(i, j - i); 
} 

放在一個靜態類,然後調用它像這樣:

var substring = s.Between("foo","bar"); 

操縱根據需要爲邊緣情況(字符串沒有找到,等)

2

我會用HtmlAgilityPack解析HTML

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(html); 

var h = doc.DocumentNode.SelectSingleNode("//ol[@id='listagem1']").InnerHtml;