HTMLAgilityPack SelectNodes 选择所有 元素
我正在用 C# 制作一个项目,它基本上是一个图像搜索相关游戏的图像屏幕抓取工具。我正在尝试使用 HTMLAgilityPack 选择所有图像元素并将它们放入 HTMLNodeCollection 中,如下所示:
//set up for checking autos
HtmlNodeCollection imgs = new HtmlNodeCollection(doc.DocumentNode.ParentNode);
imgs = doc.DocumentNode.SelectNodes("//img");
foreach (HtmlNode img in imgs)
{
HtmlAttribute src = img.Attributes["@src"];
urls.Add(src.Value);
}
请注意,urls 是一个公共列表集合:
public List<string> urls = new List<string>();
我的 foreach 循环抛出异常:
未将对象引用设置为对象的实例。
检查汽车,果然,imgs 为空。有没有更好的方法可以追踪这个问题的根源?我不知道这是我的 Xpath 还是什么。
最令人沮丧的是,我已经让它工作了,但搞乱了我的文件版本并丢失了我的工作。德普。
I am making a project in C# that's basically an image screen scraper for an image-search related game. I'm trying to use HTMLAgilityPack to select all the image elements and put them in an HTMLNodeCollection, like this:
//set up for checking autos
HtmlNodeCollection imgs = new HtmlNodeCollection(doc.DocumentNode.ParentNode);
imgs = doc.DocumentNode.SelectNodes("//img");
foreach (HtmlNode img in imgs)
{
HtmlAttribute src = img.Attributes["@src"];
urls.Add(src.Value);
}
Note that urls is a public List collection:
public List<string> urls = new List<string>();
My foreach loop is throwing an exception:
Object reference not set to an instance of an object.
Checking the autos, sure enough, imgs is null. Is there any better way I can track down the source of this problem? I have no idea if it's my Xpath or what.
The most frustrating part is that I had already gotten it to work, but messed up my file versions and lost my work. Derp.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能在以下行中有一个拼写错误:
我得到了这个对我有用(注意@位置):
You might have a typo in the following line:
I got this to work for me (notice the @ position):
这对我有用。我认为您的文档未正确加载,因此 xpath 未返回任何匹配项。
This works for me. I think your document isn't loaded correctly, hence the xpath returns no matches.