Html敏捷性问题
我正在尝试提取 div 之间的一些数据。
<div class="movie_general"><div class="img"><a href="/Movies.html" title="Watch Movie">
例如,如果我想要我使用的链接“/Movies.html”:
string hrefValue = doc.DocumentNode
.Descendants("div")
.Where(x => x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a").Attributes["href"].Value)
.FirstOrDefault();
MessageBox.Show(hrefValue);
但我在Where(x => x.Attributes["class"].Value == "movie_general")处得到一个NullReferenceException,
我做错了什么?
i am trying to extract some data between divs.
<div class="movie_general"><div class="img"><a href="/Movies.html" title="Watch Movie">
Fore example if i want the link "/Movies.html" i used:
string hrefValue = doc.DocumentNode
.Descendants("div")
.Where(x => x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a").Attributes["href"].Value)
.FirstOrDefault();
MessageBox.Show(hrefValue);
but i get a NullReferenceException at Where(x => x.Attributes["class"].Value == "movie_general")
What am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发生这种情况是因为 Linq 提供程序必须迭代文档中的所有其他节点以检查它是否与您的搜索匹配。该文档必须至少有一个没有
class
属性的div
。因此,尝试读取不存在的属性的Value
属性时会发生错误。将此替换
为此
It happens because the Linq provider must iterate through all other nodes in the document to check if it matches your search. This document must have at least one
div
which does not have aclass
attribute. So, the error happens by trying to read theValue
property of an attribute which does not exist.Replace this
with this
如果您已经知道该类并且 a 标签从属于该类,为什么不直接使用以下命令获取它:
和结果:
我在您的示例中添加了结束 div 标签,以便我可以抓取它并将其转储到我的 c 驱动器上的文件中:
If you already know the class and that the a tag is subordinate to that, why not just grab it directly using:
and the result:
I added closing div tags to your example so that I could scrape it and dumped it in a file on my c drive: