2011-08-18 86 views
3

我正在用c#編寫一個程序。 我需要知道是否有選項可以打開網站的網址並在文本中查找關鍵字。 例如,如果我的程序獲得URL http://www.google.com和關鍵字「gmail」 它將返回true。 因此,爲了得出結論,我需要知道是否有辦法去URL下載HTML文件將其轉換爲文本,所以我可以查找我的關鍵字。下載HTML文件並將其轉換爲TXT

回答

1

您應該可以按原樣打開HTML文件。 HTML文件是純文本,這意味着FileStreamStreamReader應該足以讀取該文件。

如果你真的想要的文件是.txt,您只需將文件當您下載保存爲filename.txt,而不是filename.html

+0

我覺得他的問題是actualy下載不將其轉換爲文本的頁面。有這樣的功能嗎? – atoMerz

+0

以及如何使用網址下載html? – yoni2

+0

@ yoni2:看看這個:http://stackoverflow.com/questions/599275/how-can-i-download-html-source-in-c – asfallows

2

這聽起來像你想刪除所有的HTML標籤,然後搜索結果文本。

我的第一反應是使用正則表達式:

String result = Regex.Replace(htmlDocument, @"<[^>]*>", String.Empty); 

無恥偷了這個來自: Using C# regular expressions to remove HTML tags

這表明這聽起來完全像你在找什麼HTML Agility Pack

+0

我期待知道,如果有一種方法來下載一個html文件,並將其轉換爲txt文件 – yoni2

1

在Visual Basic中工作的:

Imports System 
Imports System.IO 
Imports System.Net 

Function MakeRequest(ByVal url As String) As String 
    Dim request As WebRequest = WebRequest.Create(url) 
    ' If required by the server, set the credentials. ' 
    request.Credentials = CredentialCache.DefaultCredentials 
    ' Get the response. ' 
    Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) 
    ' Get the stream containing content returned by the server. ' 
    Dim dataStream As Stream = response.GetResponseStream() 
    ' Open the stream using a StreamReader for easy access. ' 
    Dim reader As New StreamReader(dataStream) 
    Dim text As String = reader.ReadToEnd 

    Return text 
End Function 

編輯:對於其他人發現這個頁面將來參考,您的URL通過,而這個函數會去的網頁,閱讀所有的HTML文本,並將其作爲文本字符串返回。那麼你所要做的就是解析它(搜索文件中的文本),或者如果你願意的話,你可以使用流寫入器將它保存到文本或html文件中。

0
using (WebClient client = new WebClient()) 
{ 
    client.DownloadFile("http://example.com", @"D:\filename.txt"); 
}