2017-03-02 72 views
2

首先,我嘗試了很多方法,但我無法解決我的問題。我不知道如何將我的節點放在SelectSingleNode(?)方法中。我創建了一個html路徑,以在我的c#代碼中訪問我的節點,但是如果我運行此代碼,則由於我的html路徑,我會使用NullReferenceException。我只是想讓你知道如何創建我的html方式或其他解決方案?
這是實施例的HTML代碼:我一直在試圖從網站獲取數據HtmlAgilityPack

<html> 
    <body> 
     <div id="container"> 
      <div id="box"> 
       <div class="box"> 
        <div class="boxContent"> 
         <div class="userBox"> 
          <div class="userBoxContent"> 
           <div class="userBoxElement"> 
            <ul id ="namePart"> 
             <li> 
              <span class ="namePartContent> 

              </span> 
             </li> 
            </ul> 
           </div> 
          </div> 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 

這我的C#代碼:

namespace AgilityTrial 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Uri url = new Uri("https://...."); 
      WebClient client = new WebClient(); 
      client.Encoding = Encoding.UTF8; 
      string html = client.DownloadString(url); 
      HtmlDocument doc = new HtmlDocument(); 
      doc.LoadHtml(html); 

      string path = @"//html/body/div[@id='container']/div[@id='classifiedDetail']"+ 
       "/div[@class='classifiedDetail']/div[@class='classifiedDetailContent']"+ 
       "/div[@class='classifiedOtherBoxes']/div[@class='classifiedUserBox']"+ 
       "/div[@class='classifiedUserContent']/ul[@id='phoneInfoPart']/li"+ 
       "/span[@class='pretty-phone-part show-part']"; 
      var tds = doc.DocumentNode.SelectSingleNode(path); 
      var date = tds.InnerHtml; 

       Console.WriteLine(date); 
     } 
    } 
} 

回答

1

以一個例子你namePartContent跨度節點。如果你想獲取這些數據,你會簡單地做到這一點:

doc.DocumentNode.SelectSingleNode(".//span[@class='namePartContent']")?.InnerText;

它將搜索/取單跨節點與namePartContent成爲同級車,根節點開始時,你的情況<html>;

+0

非常感謝,@ Zroq – ZpCikTi