2012-05-14 51 views
7

我想閱讀沒有html標籤和標題的網站文字。我只需要在Web瀏覽器中顯示的文本。如何閱讀c#中的網站內容?

我不需要這樣的

<html> 
<body> 
bla bla </td><td> 
bla bla 
<body> 
<html> 

我只需要文本「唧唧歪歪喇嘛」。

我已經使用webclient和httpwebrequest方法來獲取HTML內容並拆分接收到的數據,但這是不可能的,因爲如果我更改網站的標籤可能會改變。

那麼有沒有什麼辦法可以讓網站中的顯示文字變成一條條文?

+0

我認爲你需要一個HTML解析器,如果你有網頁源的控制,一個ID添加到你想得到的元素,所以要使用解析器的getElementById方法來獲取它。 – alfoks

+0

@alfoks ::你有HTML解析器的例子的任何鏈接? –

回答

4

以下是如何使用HtmlAgilityPack來做到這一點。

首先您的樣本HTML:

var html = "<html>\r\n<body>\r\nbla bla </td><td>\r\nbla bla \r\n<body>\r\n<html>"; 

加載它(在這種情況下,一個字符串):

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

如果從網絡上獲得的,相似的:

var web = new HtmlWeb(); 
var doc = web.Load(url); 

現在只選擇非空白的文本節點並修剪它們。

​​

,如果你喜歡,你可以得到這個作爲一個單一的加入字符串:

String.Join(" ", text) 

當然這隻適用於簡單的網頁的工作。任何複雜的也將返回數據,你顯然不希望節點,如JavaScript函數等

+0

真棒工作......謝謝親愛的... –

+0

::我怎麼可以訪問文本索引的索引,因爲我這樣做循環中的字符串數組這樣 'for(i = 0; i

+0

你可以直接對'text'執行:'foreach(var index in text){//做一些索引}'。或者,您可以執行'text.ToArray();'並將其作爲數組處理。 – yamen

-2
// Reading Web page content in c# program 
//Specify the Web page to read 
WebRequest request = WebRequest.Create("http://aspspider.info/snallathambi/default.aspx"); 
//Get the response 
WebResponse response = request.GetResponse(); 
//Read the stream from the response 
StreamReader reader = new StreamReader(response.GetResponseStream()); 
//Read the text from stream reader 
string str = reader.ReadLine(); 
for(int i=0;i<200;i++) 
{ 
    str += reader.ReadLine(); 

} 

Console.Write(str); 
+0

你不能像簡單的文本或regualr表達式那樣對待HTML,它不是**常規文本或語言。 – Tigran

+0

這樣你仍然可以得到所有的標記。 –

+0

@jaiff ::你能否詳細說明最後一個循環,你爲什麼只讀200個索引。 –

5

您需要使用特殊的HTML解析器。獲得諸如常規語言的內容的唯一方法。

請參見:What is the best way to parse html in C#?

+0

它不是我想要的...... –

+0

但是這是一種方式,你可以得到你所問的! – Writwick

+0

@azeemAkram:使用[HtmlAgilityPack](http://htmlagilitypack.codeplex.com/),您可以獲得您感興趣的值。最後,這是一個解析器。 – Tigran

-1

我覺得this link可以幫助你。

/// <summary> 
/// Remove HTML tags from string using char array. 
/// </summary> 
public static string StripTagsCharArray(string source) 
{ 
char[] array = new char[source.Length]; 
int arrayIndex = 0; 
bool inside = false; 

for (int i = 0; i < source.Length; i++) 
{ 
    char let = source[i]; 
    if (let == '<') 
    { 
    inside = true; 
    continue; 
    } 
    if (let == '>') 
    { 
    inside = false; 
    continue; 
    } 
    if (!inside) 
    { 
    array[arrayIndex] = let; 
    arrayIndex++; 
    } 
} 
return new string(array, 0, arrayIndex); 
} 
+0

正則表達式不應該用來解析HTML – crdx

+0

作者給你3種方法。推薦使用最後一個(StripTagsCharArray) – R4j

+2

如果在某些嵌入式JavaScript(如「if x <4」)中遇到if語句,您會如何管理此方法?答案是:不太好。正確的答案是建議HtmlAgilityPack。 – crdx

0
public string GetwebContent(string urlForGet) 
{ 
    // Create WebClient 
    var client = new WebClient(); 
    // Download Text From web 
    var text = client.DownloadString(urlForGet); 
    return text.ToString(); 
}