Ruby parse HTTP response
deeptishukla24 (2)

require 'net/http'
uri = 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).

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

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.

require 'nokogiri'
require 'rubygems'
require 'open-uri'
page = Nokogiri::HTML(open(""))
i = 0
loop do
	i += 1
	if i == 10
	puts page.css("#invisible p img")[i]["alt"]

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.

deeptishukla24 (2)

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

heyitsmarcus (309)

@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:

heyitsmarcus (309)

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

deeptishukla24 (2)

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

heyitsmarcus (309)

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