使用 HtmlAgilityPack 从 html 页面获取节点
Getting nodes from html page using HtmlAgilityPack
我的程序收集有关 Steam 用户个人资料的信息(例如游戏、徽章等)。
我使用 HtmlAgilityPack
从 html 页面收集数据,到目前为止它对我来说效果很好。
问题是在某些页面上运行良好,但在某些 - returns 空节点上或抛出异常
object reference not set to an instance of an object
举个例子。
这部分效果很好(当我获得徽章时):
WebClient client = new WebClient();
string html = client.DownloadString("http://steamcommunity.com/profiles/*id*/badges/");
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection div = doc.DocumentNode.SelectNodes("//div[@class=\"badge_row is_link\"]");
这个 returns 徽章的确切数量,然后我可以用它们做任何我想做的事。
但在这一次我做了完全相同的事情(但得到了游戏),但不知何故它一直在抛出我和我上面提到的错误:
WebClient client = new WebClient();
string html = client.DownloadString("http://steamcommunity.com/profiles/*id*/games/?tab=all");
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection div = doc.DocumentNode.SelectNodes("//*[@id='game_33120']");
我知道页面上有节点(通过 google chrome 代码视图检查)但我不知道为什么在第一种情况下它有效,但在第二种情况下它不起作用't。
当您在页面上右击并选择“查看源代码”时,您是否仍然看到 id='game_33120' 的元素?我猜你不会。我的猜测是该页面是在客户端动态构建的。因此,请求中出现的 HTML 不包含您要查找的元素。相反,一旦 Javascript 代码在浏览器中具有 运行,该元素就会出现。
原始请求似乎有一个 Javascript 部分,其中包含一个名为 rgGames 的变量,它是将在屏幕上呈现的游戏的 Javascript 数组。您应该能够从中提取信息。
我不明白这个参数“//*[@id='game_33120']”的selectNodes方法,也许这是你的错,但你可以检查一下:
- 具有批次等的 steamprofil 的真实 link 是:
http://steamcommunity.com/id/id/badges/
而不是
http://steamcommunity.com/profiles/id/badges/
- 在我访问徽章页面后,url 留在浏览器中,在游戏中 link,他们将您重定向到
http:// steamcommunity. com
也许这可以帮到你
我的程序收集有关 Steam 用户个人资料的信息(例如游戏、徽章等)。
我使用 HtmlAgilityPack
从 html 页面收集数据,到目前为止它对我来说效果很好。
问题是在某些页面上运行良好,但在某些 - returns 空节点上或抛出异常
object reference not set to an instance of an object
举个例子。
这部分效果很好(当我获得徽章时):
WebClient client = new WebClient();
string html = client.DownloadString("http://steamcommunity.com/profiles/*id*/badges/");
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection div = doc.DocumentNode.SelectNodes("//div[@class=\"badge_row is_link\"]");
这个 returns 徽章的确切数量,然后我可以用它们做任何我想做的事。
但在这一次我做了完全相同的事情(但得到了游戏),但不知何故它一直在抛出我和我上面提到的错误:
WebClient client = new WebClient();
string html = client.DownloadString("http://steamcommunity.com/profiles/*id*/games/?tab=all");
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection div = doc.DocumentNode.SelectNodes("//*[@id='game_33120']");
我知道页面上有节点(通过 google chrome 代码视图检查)但我不知道为什么在第一种情况下它有效,但在第二种情况下它不起作用't。
当您在页面上右击并选择“查看源代码”时,您是否仍然看到 id='game_33120' 的元素?我猜你不会。我的猜测是该页面是在客户端动态构建的。因此,请求中出现的 HTML 不包含您要查找的元素。相反,一旦 Javascript 代码在浏览器中具有 运行,该元素就会出现。
原始请求似乎有一个 Javascript 部分,其中包含一个名为 rgGames 的变量,它是将在屏幕上呈现的游戏的 Javascript 数组。您应该能够从中提取信息。
我不明白这个参数“//*[@id='game_33120']”的selectNodes方法,也许这是你的错,但你可以检查一下:
- 具有批次等的 steamprofil 的真实 link 是:
http://steamcommunity.com/id/id/badges/
而不是
http://steamcommunity.com/profiles/id/badges/
- 在我访问徽章页面后,url 留在浏览器中,在游戏中 link,他们将您重定向到
http:// steamcommunity. com
也许这可以帮到你