2017-04-09 35 views
0

我試圖從這個網站標籤如何使用C#

sometext

提取文本,我有這樣的代碼來提取網頁數據:

using System; 
using System.Net; 
using HtmlAgilityPack; 

namespace GC_data_console 
{ 
    class Program 
    { 
     public static void Main(string[] args) 
     { 

      using (var client = new WebClient()) 
      { 
       // Download the HTML 
       string html = client.DownloadString("https://www.requestedwebsite.com"); 


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


       foreach(HtmlNode link in 
         doc.DocumentNode.SelectNodes("//span")) 
       { 
        HtmlAttribute href = link.Attributes["id='example1'"]; 


        if (href != null) 
        { 
        Console.WriteLine(href.Value.ToString()); 
         Console.ReadLine(); 
        } 
       } 
       } 
      } 
     } 
    } 
} 

但我仍然沒有得到文字「sometext」。

但是,如果我插入HtmlAttribute href = link.Attributes [「id」]; 我會得到所有的ID名稱。

我在做什麼錯了?

+0

您可以分享您試圖獲取內容的實際URL嗎?你也試圖獲得'HtmlAttribute'的值而不是元素。你需要嘗試獲得的是'link.InnerText'。 –

+0

你好,例如從這個網頁https://www.geocaching.com/geocache/GC257YR_slivercup-studios-east ,我想從標籤中獲取文本: SliverCup Studios East Shiwers

+0

知道了....你嘗試了我建議的另一種方式嗎?你是否也調試過並檢查你是否獲得了正確的元素? –

回答

1

您需要先了解HTML節點和HTMLAttribute之間的區別。你的代碼遠沒有解決問題。

HTMLNode表示HTML中使用的標籤,如span,div,p,a等等。 HTMLAttribute表示用於HTMLNode的屬性,例如href屬性用於astyle,class,id,name等屬性用於幾乎所有HTML標籤。

在下面HTML

<span id="firstName" style="color:#232323">Some Firstname</span> 

span是HTMLNode而idstyle是HTMLAttributes。您可以使用HtmlNode.InnerText屬性獲得值Some FirstName

也從HtmlDocument中選擇HTMLNode並不那麼簡單。你需要提供適當的XPath來選擇你想要的節點。

現在在您的代碼中,如果您想要獲得<span id="ctl00_ContentBody_CacheName">SliverCup Studios East</span>(它是someurl.com的HTML的一部分)中編寫的文本,則需要編寫以下代碼。

using (var client = new WebClient()) 
{ 
    string html = client.DownloadString("https://www.someurl.com"); 

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

    //Selecting all the nodes with tagname `span` having "id=ctl00_ContentBody_CacheName". 
    var nodes = doc.DocumentNode.SelectNodes("//span") 
     .Where(d => d.Attributes.Contains("id")) 
     .Where(d => d.Attributes["id"].Value == "ctl00_ContentBody_CacheName"); 

    foreach (HtmlNode node in nodes) 
    { 
     Console.WriteLine(node.InnerText); 
    } 
} 

上面的代碼將選擇所有span標籤,它們可直接在HTML的文檔節點下。您需要使用不同的XPath,位於層次結構內部的標籤。

這應該有助於您解決問題。

+0

謝謝!這解決了我的問題,也感謝解釋。這是很久以前,因爲我已經在html中創建了一些東西。 現在我通過WebClient以某種方式「登錄」,因此我可以存儲數據,這些數據僅提供給登錄用戶,但我將在未來進行此操作。 – Shiwers