为什么Html.AgilityPack错过一些图像标记?标记、图像、Html、AgilityPack

2023-09-06 18:07:43 作者:一江圆月

我使用的HTML敏捷包,做了这样的事情

  HtmlWeb网=新HtmlWeb();
 的HTMLDocument文档= web.Load(http://test.com);

。诠释计数= doc.DocumentNode.SelectNodes(// IMG)计数();
 

我得到 38 回来了。

当我去到该页面,并做 $('IMG')的大小(); 我得到 43 回来。为什么有区别吗?为// IMG只是在寻找根的?

这就是为什么我可能会丢失一些?

解决方案   

时的// IMG只是在寻找   根的?

Html Agility Pack 解析HTML

没有它寻找子节点(子女,孙子女,目前节点等)。在XPath EX pression从文档中选择所有的图片。

  

当我去到该页面,做$('IMG')的大小()。我得到43回来。

我的假设 - 一些图片是通过JavaScript动态创建。 HtmlAgilityPack不能处理这个问题。

顺便说一句,对于 http://test.com 我得到了87图像节点与AgilityPack( doc.DocumentNode.SelectNodes( // IMG)。COUNT()),并从丁目控制台87的图像节点( $('IMG')。大小() )。

修改: HtmlWeb.Load()方法在内部使用的 的WebRequest 类来获取数据。 AgilityPack的作用的正确解析数据的。这是完全可能的,一些网络资源换取相同的URI不同的内容取决于某些请求标头的如用户代理等。例如。 用户代理头可以通过 HtmlWeb.UserAgent 属性进行设置。

I am using the html agility pack and did something like this

HtmlWeb web = new HtmlWeb();
 HtmlDocument doc = web.Load("http://test.com");

int count = doc.DocumentNode.SelectNodes("//img").Count();

I get 38 back.

When I go to that page and do $('img').size(); I get 43 back. Why is there a difference? Is "//img" just looking for root ones?

Is that why I might be missing some?

解决方案

Is "//img" just looking for root ones?

No it looking for descendant nodes (children, grandchildren, etc. of the current node). Your xpath expression selects all the images from the document.

When I go to that page and do $('img').size(); I get 43 back.

My assumption - some of the images are created dynamically via javascript. HtmlAgilityPack cannot handle this.

By the way, for the http://test.com I got 87 image nodes with AgilityPack (doc.DocumentNode.SelectNodes("//img").Count()), and 87 image nodes from the Chome console ($('img').size()).

EDIT: HtmlWeb.Load() method internally uses WebRequest class to get data. The role of AgilityPack is to parse the data correctly. It's completely possible that some web resources return different content for the same URI depending on some of request headers like User-Agent and others. E.g. User-Agent header could be set via HtmlWeb.UserAgent property.