Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, fetch first image from a text [closed]

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
like image 589
Mich Dart Avatar asked Dec 06 '25 04:12

Mich Dart


2 Answers

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

See live demo here

doc.xpath('//img').first.attr('src').text

like image 36
Hugo Logmans Avatar answered Dec 08 '25 18:12

Hugo Logmans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!