Nokogiri gem vs. opening by hand - ruby-on-rails

I can't get Nokogiri to return the same thing I see when I go to a page and "View Source". And for the life of me can't figure out why.
This is the page I am looking at:
http://www.amazon.com/gp/product/B009NWFP5Q
And as you can see it returns a shoe that's orange..and if I view the source and find the link I'm looking for by searching for "hiRes" twice, I get:
http://ecx.images-amazon.com/images/I/71b75uTtzDL.UL1500.jpg
However, if I run this code with Nokogiri:
require 'nokogiri'
require 'open-uri'
require 'uri'
url = "http://www.amazon.com/gp/product/B009NWFP5Q"
doc = Nokogiri::HTML(open(url))
pic = doc.css('div#imageBlock_feature_div script')[0]
puts pic
and look for the link in the same position I get this image:
http://ecx.images-amazon.com/images/I/81R97WG9nyL.UL1500.jpg
which is a BLUE shoe!!! Arghhh..
Any idea why??

Maybe the color being shown is somehow based on your session or dynamic attributes assigned to a cookie stored in your browser. Find a way to provide a URL that will return exactly what you are looking for. It may also be possible to provide a cookie using the http client code but that seems like a plan B.

Related

Why it is returning an empty array while it has content?

I am trying to get auto-corrected spelling from Google's home page using Nokogiri.
For example, if I am typing "hw did" and the correct spelling is "how did", I have to get the correct spelling.
I tried with the xpath and css methods, but in both cases, I get the same empty array.
I got the XPath and CSS paths using FireBug.
Here is my Nokogiri code:
#requ=params[:search]
#requ_url=#requ.gsub(" ","+") //to encode the url(if user inputs space than it should be convet into + )
#doc=Nokogiri::HTML(open("https://www.google.co.in/search?q=#{#requ_url}"))
binding.pry
Here are my XPath and CSS selectors:
Using XPath:
pry(#<SearchController>)> #doc.xpath("/html/body/div[5]/div[2]/div[6]/div/div[4]/div/div/div[2]/div/p/a").inspect
=> "[]"
Using CSS:
pry(#<SearchController>)> #doc.css('html body#gsr.srp div#main div#cnt.mdm div.mw div#rcnt div.col div#center_col div#taw div div.med p.ssp a.spell').inner_text()
=> ""
First, use the right tools to manipulate URLs; They'll save you headaches.
Here's how I'd find the right spelling:
require 'nokogiri'
require 'uri'
require 'open-uri'
requ = 'hw did'
uri = URI.parse('https://www.google.co.in/search')
uri.query = URI.encode_www_form({'q' => requ})
doc = Nokogiri::HTML(open(uri.to_s))
doc.at('a.spell').text # => "how did"
it works fine with "how did",check it with "bnglore" or any one word string,it gives an error. the same i was facing in my previous code. it is showing undefined method `text'
It's not that hard to figure out. They're changing the HTML so you have to change your selector. "Inspect" the suggested word "bangalore" and see where it exists in relation to the previous path. Once you know that, it's easy to find a way to access the word:
doc.at('span.spell').next_element.text # => "bangalore"
Don't trust Google to do things the easy way, or even the best way, or be consistent. Just because they return HTML one way for words with spaces, doesn't mean they're going to do it the same way for a single word. I would do it consistently, but they might be trying to discourage you from mining their pages so don't be surprised if you see variations.
Now, you need to figure out how to write code that knows when to use one selector/method or the other. That's for you to do.

Using Nokogiri I am unable to find certain nodes in a document

When trying to search a document for ysr-bio-data ("Height" value) on this page http://sports.yahoo.com/footballrecruiting/football/recruiting/player-Jonathan-Allen-125805
The node is nil. Is this because nokogiri is getting the page before this section is populated? Or is it that the nokogiri object isn't storing the whole page into it's object?
Below is some sample code of how I'm trying to retrieve the data. Thanks!
doc = Nokogiri::HTML(open('http://sports.yahoo.com/footballrecruiting/football/recruiting/player-Jonathan-Allen-125805'))
doc.css('ul#ysr-bio-data')
If I need to provide any additional information please let me know. Thanks!
Edit: Fixed incorrect syntax.
Sorry bud, but there is javascript that needs to run on the page for those cells to be filled out.
you can do this tho.. make the javascript run in a web-browser..
require 'nokogiri'
require 'watir-webdriver' #http://watir.com/
$browser = Watir::Browser.start "http://sports.yahoo.com/footballrecruiting/football/recruiting/player-Jonathan-Allen-125805"
doc = Nokogiri::HTML.parse($browser.html)
doc.css("ul#ysr-bio-data").text
=> "Ht:6'3\"Wt:263 lbs40:4.5 secsBench Max:280Class:2013 (High School)\t"
We're basically replacing open-uri with watir.
Hope this helps.
I found another question on stackoverflow that provided a means to solving my issue.
HTML is read before fully loaded using open-uri and nokogiri

using 'puts' to get information from external domain

ive just started with ruby on rails the other day and i was wandering is it possible to using the puts function to get the content of a div from a page on an external page.
something like puts "http://www.example.com #about"
would something like this work ? or would you have to get the entire page and then puts that section that you wanted ?
additionaly if the content on the "example.com" #about div is constantly changing would puts constantly update its output or would it only run the script each time the page is refreshed ?
The open-uri library (for fetching the page) and the Nokogiri gem (for parsing and retrieving specific content) can assist with this.
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::HTML(open('http://www.example.com/'))
puts doc.at('#about').text
puts will not work that way. Ruby makes parsing HTML fairly easy though. Take a look at the Nokogirl library, and you can use xpath queries to get to the div you want to print out. I believe you would need to reopen the file if the div changes, but I'm not positive about that - you can easily test it (or someone here can confirm or reject that statement).

Ruby on Rails - Converting Twitter #mentions, #hashtags and URLs within a string

Let's say I have a string which contains text grabbed from Twitter, as follows:
myString = "I like using #twitter, because I learn so many new things! [line break]
Read my blog: http://www.myblog.com #procrastination"
The tweet is then presented in a view. However, prior to this, I'd like to convert the string so that, in my view:
#twitter links to http://www.twitter.com/twitter
The URL is turned into a link (in which the URL remains the link text)
#procrastination is turned into https://twitter.com/i/#!/search/?q=%23procrastination, in which #procrastination is the link text
I'm sure there must be a gem out there that would allow me to do this, but I can't find one. I have come across twitter-text-rb but I can't quite work out how to apply it to the above. I've done it in PHP using regex and a few other methods, but it got a bit messy!
Thanks in advance for any solutions!
The twitter-text gem has pretty much all the work covered for you. Install it manually (gem install twitter-text, use sudo if needed) or add it to your Gemfile (gem 'twitter-text') if you are using bundler and do bundle install.
Then include the Twitter auto-link library (require 'twitter-text' and include Twitter::Autolink) at the top of your class and call the method auto_link(inputString) with the input string as the parameter and it will give you the auto linked version
Full code:
require 'twitter-text'
include Twitter::Autolink
myString = "I like using #twitter, because I learn so many new things! [line break]
Read my blog: http://www.myblog.com #procrastination"
linkedString = auto_link(myString)
If you output the contents of linkedString, you get the following output:
I like using #<a class="tweet-url username" href="https://twitter.com/twitter" rel="nofollow">twitter</a>, because I learn so many new things! [line break]
Read my blog: http://www.myblog.com <a class="tweet-url hashtag" href="https://twitter.com/#!/search?q=%23procrastination" rel="nofollow" title="#procrastination">#procrastination</a>
Use jQuery Tweet Linkify
A small jQuery plugin that transforms #mention texts into hyperlinks pointing to the actual Twitter profile, #hashtag texts into real hashtag searches, as well as hyperlink texts into actual hyperlinks

Construct URLs after scraping for image paths

I'm trying to scrape a web URL inputed by the user and then output an array of valid non-broken image elements with absolute paths in HTML. I'm using Nokogiri for scraping and I want to know if there is anything I can use to easily process the unpredicatble URLs provided by user and image paths scraped short of figuring out how to write something from scratch.
Examples:
http://domain.com/ and /system/images/image.png
=> http://domain.com/system/images/image.png
http://sub.domain.com and images/common/image.png
=> http://sub.domain.com/images/common/image.png
http://domain.com/dir/ and images/image.png
=> http://domain.com/dir/images/image.png
http://domain.com/dir and /images/small/image.png
=> http://domain.com/images/small/image.png
http://domain.com and http://s3.amazon-aws.com/bucket/image.png
=> http://s3.amazon-aws.com/bucket/image.png
Instead of downloading the pages and using Nokogiri, I would recommend using Mechanize. It is built on top of Nokogiri, so everything you can do with Nokogiri you can do with Mechanize, but it adds a lot of useful functionality for scraping/navigating. It will take care of the relative URL problem you describe above.
require 'rubygems'
require 'mechanize'
url='http://stackoverflow.com/questions/5903218/construct-urls-after-scraping-for-image-paths/5903417'
Mechanize.new.get(url) {|page| puts page.image_urls.join "\n"}
If you really want to do it yourself (instead of using Mechanize, say), use URI::join:
require 'uri'
URI::join("http://domain.com/dir", "/images/small/image.png")
# => http://domain.com/images/small/image.png
Note that you have to respect the HTML page's BASE tag if there is one...

Resources