Within a Ruby class, I want to parse and fetch the first occurance of an image inside some text that is saved in a database. In particular, I want to collect all src attributes.
Will Nokogiri help me? How can I do it?
Edit1:
I wrote:
// database stuff...
doc = Nokogiri::HTML(my_html)
doc.search('img') do |img_tag|
puts img_tag
end
But I'm not able to collect the image tags.
Edit2:
I found the solution:
doc.search('img').each do |img_tag|
puts img_tag.attributes['src']
end
try this:
require 'nokogiri'
str = "some text <img src='/some/path' /> some another text"
doc = Nokogiri::HTML(str)
if img = doc.xpath('//img').first
p img.attr('src')
end
doc.xpath('//img').first.attr('src').text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With