使用HtmlAgilityPack从网站上抓取数据时,子节点的文本出现问题

时间:2020-07-03 02:51:36

标签: c# html xpath html-agility-pack

希望有人可以帮助这个新手。

我为此子节点尝试了许多路径,但我无法弄清楚。

HTML部分:

 <div class="center-block"> == $0
    <div class="match-time" id="dvStatusText">MS</div>
    <div class="match-score" id="dvScoreText">4 - 0</div>
    <div class="hf-match-score" id="dvHTScoreText">İY : 3- 0</div>
 </div>

我的代码:

Uri url = new Uri("http://arsiv.mackolik.com/Mac/3213138/");
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
try
   {
      string html = client.DownloadString(url);
      HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
      doc.LoadHtml(html);
      HtmlNodeCollection results = doc.DocumentNode.SelectNodes("//*[@class='center-block']"); // 
       if (results != null)
       {
          for (int i = 0; i < results.Count; i++)
           { 
             var t1 = results[i].SelectSingleNode("//*[@class='match-score']").InnerText; // (FT)
             var t2 = results[i].SelectSingleNode("//*[@id='dvHTScoreText']").InnerText; // ht
             listBox1.Items.Add(t2.ToString());
           }
    }

我来自InnerHtml结果的问题:

 <div class="match-time" id="dvStatusText">MS</div>
 <div class="match-score" id="dvScoreText">4 - 0</div>
 <div class="hf-match-score" id="dvHTScoreText"></div> // this element has always contains text.

我尝试了不同的方法来解决此问题,但我一无所获。我可以抓取“ class = match time”或“ class = match-score”。但是我不能“ class = hf-match-score”。我尝试用班级或编号进行刮擦。不同的方式存在相同的问题。 请告诉我一种方法。非常感谢。

1 个答案:

答案 0 :(得分:0)

半场得分用Javascript显示。您需要Selenium或类似的工具来访问此元素。

或者,您可以直接从后台加载的JSON中获取数据。 Python中的一段代码(我想您可以在c#中做同样的事情):

import requests
from lxml import html

# We set up the download url (obtained in the network tab of the developer tool) and the mandatory header

url = 'http://arsiv.mackolik.com/Match/MatchData.aspx?t=dtl&id=3213138&s=0'
hd = {'Referer': 'http://arsiv.mackolik.com/Mac/3213138/'}

# We download and parse the json

data = requests.get(url,headers=hd)
val= data.json()

# We extract values of interest

print(val["d"]["s"],val["d"]["ht"],sep="\n")

输出:

4 - 0
3 - 0