gpt4 book ai didi

ruby - 如何在 Ruby 中获取 HTML 图像标签属性值?

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:28 25 4
gpt4 key购买 nike

我有这个 HTML 代码:

<img src="../../../media/test.jpg" alt="test" />

但只想要这个:

"../../../media/test.jpg"

我如何在 Ruby 中获得它?

最佳答案

使用 Nokogiri

require 'nokogiri'

doc = Nokogiri::XML::DocumentFragment.parse <<-end
<img src="../../../media/test.jpg" alt="test" />
end
node = doc.at_css('img')
# => #(Element:0x49a28e8 {
# name = "img",
# attributes = [
# #(Attr:0x49a2da2 { name = "src", value = "../../../media/test.jpg" }),
# #(Attr:0x49a2e24 { name = "alt", value = "test" })]
# })
node.attributes
# => {"src"=>
# #(Attr:0x50324ba { name = "src", value = "../../../media/test.jpg" }),
# "alt"=>#(Attr:0x50324b0 { name = "alt", value = "test" })}
node.keys
# => ["src", "alt"]
node.values
# => ["../../../media/test.jpg", "test"]
node['src']
# => "../../../media/test.jpg"
node['alt']
# => "test"

如果你想删除属性alt,你可以执行以下操作:

node.delete('alt')
node
# => #(Element:0x49a28e8 {
# name = "img",
# attributes = [
# #(Attr:0x49a2da2 { name = "src", value = "../../../media/test.jpg" })]
# })
node.values
# => ["../../../media/test.jpg"]

关于ruby - 如何在 Ruby 中获取 HTML 图像标签属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17754686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com