简体   繁体   English

在Nokogiri中访问HTML属性

[英]Accessing HTML attributes in Nokogiri

Here is the code I'm using: 这是我正在使用的代码:

location = block.xpath("*/img")
puts location

And this outputs: 并输出:

<img src="/images/p.gif" height="1" width="0">

What I want to do is get the width attribute out of the html, but I can't seem to get that too work. 我想做的是从html中获取width属性,但是我似乎做不到。 I think I need to put ['width'] somewhere in my code, and I've tried following various examples online but couldn't get it to work. 我认为我需要在代码中放置['width'] ,并且我尝试了在线以下各种示例,但无法使其正常工作。

CSS选择器往往更容易且更具可读性:

puts block.at('img')[:height]

Take a look at the xpath syntax from this XPath Tutorial . 看一下XPath Tutorial中的xpath语法。

Try block.at_xpath("*/img")["width"] , or */img/@width if there is just one element. 尝试使用block.at_xpath("*/img")["width"] ,如果只有一个元素,则尝试*/img/@width

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM