【问题标题】:Problem with subnode's text when scraping data from a website with HtmlAgilityPack使用 HtmlAgilityPack 从网站抓取数据时出现子节点文本的问题
【发布时间】:2020-10-23 17:28:52
【问题描述】:

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

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

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”。我试过用类或 id 刮擦。不同的方式同样的问题。 请告诉我一个方法。非常感谢。

【问题讨论】:

  • 如果您将 XPath 表达式更改为:.//*[@id='dvHTScoreText'](即:. 在表达式开头以指定您正在从上下文节点工作),输出会是什么?
  • 我试过了,结果一样。但我意识到这一点,当我下载 html 文件时,这个元素 (class="hf-match-score") 没有文本。怎么可能
  • MS
    4 - 0

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


【解决方案1】:

半场得分以 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

【讨论】:

  • 非常感谢我的英雄 :) 我用硒做到了。我瞎了,你睁开眼睛:)
猜你喜欢
  • 2011-03-07
  • 1970-01-01
  • 2019-01-18
  • 2020-11-24
  • 1970-01-01
  • 2019-09-26
  • 2014-11-24
  • 1970-01-01
  • 2021-01-23
相关资源
最近更新 更多