How to get img src using Nokogiri and at_css

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

So far, all I get is either zero or an empty string.

This is 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.

+7
ruby ruby-on-rails ruby-on-rails-4 nokogiri
source share
1 answer

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 how you get the img tag. You are trying to get img tags inside #productMainImage , but this id is the image itself, so it will not find anything.

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

+10
source share