2017-04-06 61 views
0

我想獲取網頁的html。然後用這個html有兩個元素,我有我想讀的xpath。我對這個主題知之甚少。將網頁html下載到html文檔

當我搜索時,我不斷看到例子,但他們加載的網址,並把HTML的字符串。但是我相信因爲我有兩個xpath,所以將網頁的html作爲html文檔而不是字符串下載會更好,還是我錯了?

using (WebClient client = new WebClient()) { 
    string s = client.DownloadString(url); 
} 

那麼如何下載網頁的html到我可以搜索的html文檔?

+1

的可能的複製[什麼是C#來解析HTML的最佳方式?](http://stackoverflow.com/questions/56107/what-is-the-best-way-to- parse-html-in-c) – mason

+0

@mason我應該添加我想這樣做,而不使用任何第三方代碼。我無法在我的工作場所下載第三方軟件 – mHelpMe

+0

您能否提供一些有關XPath查詢的信息? – levent

回答

-2

可以使用的StreamWriter來下載的數據寫入文件:

string s = string.Empty; 
using(WebClient client = new WebClient()) 
{ 
    string s = client.DownloadString(url); 
} 

using (FileStream fs = new FileStream("test.html", FileMode.Create)) 
{ 
    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) 
    { 
    w.WriteLine(s); 
    } 
    } 
+2

您已經問過如何將html下載到文件中,然後downvoted包含確切信息的答案,即使不使用任何外部庫?不是很酷。 –

+0

**將網頁的html作爲html文檔下載會更好** - 他試圖說他需要找出如何將html文檔解析爲可通過xpath搜索的結構化文檔。 https://www.w3schools.com/xml/xpath_intro.asp。我同意這個問題很不明確。 –

1

我這是怎麼做到這一點。

  1. 所以首先你在字符串變量中定義你的url。
  2. 然後你下載字符串HttpWebRequest類。
  3. 我使用HtmlAgilityPack,所以你應該把它包含在你的項目中(例如使用Nugger)。
  4. 創建對象HtmlDocument,並將數據加載到此對象。
  5. 現在您可以瀏覽您的HtmlDocument

    string urlAddress = "url.com"; 
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress); 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    string data = ""; 
    if (response.StatusCode == HttpStatusCode.OK) 
    { 
    Stream receiveStream = response.GetResponseStream(); 
    StreamReader readStream = null; 
    
    if (response.CharacterSet == null) 
    { 
        readStream = new StreamReader(receiveStream); 
    } 
    else 
    { 
        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); 
    } 
    
    data = readStream.ReadToEnd(); 
    
    
    response.Close(); 
    readStream.Close(); 
    } 
    
    HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument(); 
    document2.LoadHtml(data);