var imageNode = doc.DocumentNode.SelectSingleNode("//table[@id='tickerStats']/tbody/tr/td/img");
string imageText = imageNode.Attributes["src"].Value;
基本上只是抓取具有 id 的最近元素,然后沿着树走到你想要的位置。
或者,这也可以工作,并且看起来更干净一些(因为只要只有一张图像,您并不真正关心表本身中的 DOM 结构):
var statsNode = doc.DocumentNode.SelectSingleNode("//table[@id='tickerStats']");
var imageNode = statsNode.SelectSingleNode(".//img");
string imageText = imageNode.Attributes["src"].Value;
Based on your URL this worked for me:
var imageNode = doc.DocumentNode.SelectSingleNode("//table[@id='tickerStats']/tbody/tr/td/img");
string imageText = imageNode.Attributes["src"].Value;
Basically just grabbing the closest element that has an id, then walking the tree down to where you want to be.
Alternatively this would work too and seems a little cleaner (since you don't really care about the DOM structure in the table itself as long as there is just one image):
var statsNode = doc.DocumentNode.SelectSingleNode("//table[@id='tickerStats']");
var imageNode = statsNode.SelectSingleNode(".//img");
string imageText = imageNode.Attributes["src"].Value;
This selects any attribute named src of any element named img that is a child of a td that is a child of a tr that is a child of a tbody that is a child of any table in the document, that has an id attribute with value 'tickerStats'.
If you need just the string value of this attribute (assuming the above XPath expression selects a single attribute node), use:
发布评论
评论(2)
根据你的 URL,这对我有用:
基本上只是抓取具有 id 的最近元素,然后沿着树走到你想要的位置。
或者,这也可以工作,并且看起来更干净一些(因为只要只有一张图像,您并不真正关心表本身中的 DOM 结构):
Based on your URL this worked for me:
Basically just grabbing the closest element that has an id, then walking the tree down to where you want to be.
Alternatively this would work too and seems a little cleaner (since you don't really care about the DOM structure in the table itself as long as there is just one image):
使用:
选择名为
img
的任何名为img
的元素中名为src
的任何属性,该元素是td
的子元素。tr
的子级,该tr
是tbody
的子级,而tbody
又是文档中具有的任何
属性,值为“tickerStats”。table
的子级id如果您只需要此属性的字符串值(假设上面的 XPath 表达式选择单个属性节点),请使用:
Use:
This selects any attribute named
src
of any element namedimg
that is a child of atd
that is a child of atr
that is a child of atbody
that is a child of anytable
in the document, that has anid
attribute with value 'tickerStats'.If you need just the string value of this attribute (assuming the above XPath expression selects a single attribute node), use: