How do I print the text in between a span tag using Nokogiri?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How do I print the text in between a span tag using Nokogiri?



I've been playing around with Nokogiri on Ruby recently, and I've run into a problem where when I want to puts a specific item to the console, but it prints out blank spaces only. I've tried puts other text to the console such as the products names and that works fine. So I'm at a loss as to what I'm doing wrong here.



Here's the code.


url = "https://www.ikea.com/us/en/search/?query=chair"
doc = Nokogiri::HTML(open(url))

doc.css('.prodHeader').each do |item|
price = item.css('span#txtPrice').text
puts price
end



Heres the HTML block I'm referencing.


<span id="txtPriceProduct1" class="prodPrice" style="clear:both;">
$89.00
</span>





txtPrice doesn't seem to appear in the HTML you've shown
– matthewd
Aug 10 at 5:14


txtPrice





Did you try running the code?
– Eric Maxwell
Aug 10 at 5:38





That should be: #txtPriceProduct1
– pguardiario
Aug 10 at 5:45


#txtPriceProduct1




2 Answers
2



The element with id #txtPriceProduct1 is a sibling of .prodHeader, not a child. Your code only searches through the children of .prodHeader, that’s why the element containing the price is not found.


#txtPriceProduct1


.prodHeader


.prodHeader



This code prints out all the prices (stripped of whitespace):


doc.css('.prodHeader').each do |item|
price = item.next_element.text
puts price.strip
end



You are seeing empty lines because there is no matching node span#txtPrice, causing it to return empty NodeSet, calling text on which returns empty string.
You might want to do:


span#txtPrice


NodeSet


text


doc.css('.prodHeader').each do |item|
puts "#item.css('.prodName').text.strip - #item.css('+ span').text.strip"
end

LÅNGFJÄLL - $149.00
IKEA PS LÖMSK - $69.99
LANGUR - $119.00
HATTEFJÄLL - $249.00
EKERÖ - $179.00
NORRARYD - $99.00
HATTEFJÄLL - $219.00
POÄNG - $79.00
HENRIKSDAL - $69.00
VÄNNÄS - $449.00
SJÄLLAND - $95.00
TULLSTA - $149.00
LÅNGFJÄLL - $179.00
BERNHARD - $169.00
POÄNG - $129.00
SJÄLLAND - $95.00
POÄNG - $129.00
INDUSTRIELL - $149.00
INDUSTRIELL - $89.00
LÅNGFJÄLL - $199.00
TULLSTA - $30.00
UTTRAN - $599.00
FJÄLLBERGET - $199.00
STRANDMON - $99.00
EKERÖ - $149.00



In above, we are getting .prodHeader and extracting the product name with the child selector, and extracting the price with + span using sibling selector


.prodHeader


+ span






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered