Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the img src using Nokogiri and at_css

I'm trying to get the src value of a block of HTML. I am specifically trying to achieve this using the at_css and not using XPath.

So far all I'm getting is either nil or a blank string.

This is the HTML:

<div class="" id="imageProductContainer">
  <a id="idLinkProductMainImage" href='URL'>
    <img id="productMainImage" src="SRC.jpg" alt="alt" title="A Title" align="left" class="product_image_productpage_main selectorgadget_selected">
  </a>  
</div>

The code I have is:

item = page.doc.at_css("#productMainImage img").text.strip unless page.doc.at_css("#productMainImage img").nil?

puts item #prints blank
item = item["src"]
puts item #prints blank

Where page.doc is the Nokogiri HTML element.

like image 755
David Sigley Avatar asked May 20 '14 13:05

David Sigley


1 Answers

If you need the src attribute, you can do it like this:

pace.doc.at_css('#idLinkProductMainImage img').attr('src')

Also, I believe the problem is the way you are getting the img tag. You are trying to get all img tags inside #productMainImage, but this id is the image itself, so it will find nothing.

If you use the link id #idLinkProductMainImage, then you have a img tag to search inside it.

like image 121
MurifoX Avatar answered Oct 22 '22 05:10

MurifoX