2
Ruby parse HTTP response
deeptishukla24 (2)

require 'net/http'
uri = URI('https://www.random.org/dice/?num=10')
Net::HTTP.get(uri)

I'm using the above code to call this random dice generator.
I'm able to get the entire http response using the get method above.
But I'm stuck on how to access the result from that big HTML string?
I'm just trying to access the individual dice values (10 in this case).
Thanks!

You are viewing a single comment. View All
2
heyitsmarcus (280)

Absolutely! I just found Nokogiri, made a simple little repl, pulling out the HTML from the page.

First, I did an Inspect on the dice rolling page using Chrome's developer tools to see that the dice can be selected from #invisible p img. There's no other good classes or ids to attach to because the HTML is loosely typed after the #invisible selector.

Then, using Nokogiri, I grab the HTML of the page, create a simple for loop going from 0-9 (for 10 dice), and output to the console the results of grabbing the element at i position with the selector #invisible p img and the alt attribute which correlates to the rolled number.

It ends up becoming 13 lines of code.

https://repl.it/@heyitsmarcus/Ruby-Test

require 'nokogiri'
require 'rubygems'
require 'open-uri'
page = Nokogiri::HTML(open("https://www.random.org/dice/?num=10"))
i = 0
loop do
	i += 1
	if i == 10
		break
	end
	
	puts page.css("#invisible p img")[i]["alt"]
end

If this solves your problem, please consider upvoting and marking my answer as the accepted to close this question. I will still continue to answer questions.

1
deeptishukla24 (2)

@heyitsmarcus Thanks a ton!! This is perfect! I upvoted the answer. How do I mark it as the accepted answer?

1
heyitsmarcus (280)

@deeptishukla24 I think there is a check mark below the upvote icon in the top comment I made with the answer. I think you have to put your mouse over it for it to show up.

I'm referring back to this page on repl: https://repl.it/talk/announcements/Mark-your-question-as-heavy-check-markanswered-on-Repl-Talk/13187?order=new

1
heyitsmarcus (280)

@deeptishukla24 You are very welcome, and welcome to the Repl community! =]

2
deeptishukla24 (2)

@heyitsmarcus Thanks. One small change - its printing only 9 values. Changing i to -1 fixed it.

1
heyitsmarcus (280)

@deeptishukla24 Ah good call that way it will go to 0 before the initial puts hit. Awesome!