在 Nokogiri 中获取属性值以提取链接 URL [英] Getting attribute's value in Nokogiri to extract link URLs
本文介绍了在 Nokogiri 中获取属性值以提取链接 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的文档:
<a href="http://google.com">link</a>
我无法让 Nokogiri 为我获取 href
属性的值.我想将地址作为字符串存储在 Ruby 变量中.
解决方案
html = <<HTML<div id="块"><a href="http://google.com">link</a>
HTMLdoc = Nokogiri::HTML(html)doc.xpath('//div/a/@href')#=>[#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
或者,如果您想更具体地了解 div:
<代码>>>doc.xpath('//div[@id="block"]/a/@href')=>[#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]>>doc.xpath('//div[@id="block"]/a/@href').first.value=>http://google.com"
I have a document which look like this:
<div id="block">
<a href="http://google.com">link</a>
</div>
I can't get Nokogiri to get me the value of href
attribute. I'd like to store the address in a Ruby variable as a string.
解决方案
html = <<HTML
<div id="block">
<a href="http://google.com">link</a>
</div>
HTML
doc = Nokogiri::HTML(html)
doc.xpath('//div/a/@href')
#=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
Or if you wanna be more specific about the div:
>> doc.xpath('//div[@id="block"]/a/@href')
=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
>> doc.xpath('//div[@id="block"]/a/@href').first.value
=> "http://google.com"
这篇关于在 Nokogiri 中获取属性值以提取链接 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文