Formatting HTML into CSV - ruby

I'm scraping a website using Ruby with Nokogiri.
This script creates a local text file, opens a URL, and writes to the file if the expression tr td is met. It is working fine.
require 'rubygems'
require 'nokogiri'
require 'open-uri'
DOC_URL_FILE = "doc.csv"
url = "http://www.SuperSecretWebSite.com"
data = Nokogiri::HTML(open(url))
all_data = data.xpath('//tr/td').text
File.open(DOC_URL_FILE, 'w'){|file| file.write all_data}
Each line has five fields which I would like to run horizontally then go to the next line after five cells are filled. The data is all there but isn't usable.
I was hoping to learn or get the code from someone that knows how to create a CSV formatting code that:
While the script is reading the code, dump every new td /td x5 into its own cells horizontally.
Go to the next line, etc.
The layout of the HTML is:
<tr>
<td>John Smith</td>
<td>I live here 123</td>
<td>phone ###</td>
<td>Birthday</td>
<td>Other Data</td>
</tr>
What the final product should look like.
http://picpaste.com/pics/Screenshot-KRnqRGrP.1361813552.png
current output
john Smith I live here 123 phone ### Birthday Other Data,

This is pretty standard code to walk a table and extract its cells into an array of arrays. What you do with the data at that point is up to you, but it's a very easy to pass it to CSV.
require 'nokogiri'
require 'pp'
doc = Nokogiri::HTML(<<EOT)
<table>
<tr>
<td>John Smith</td>
<td>I live here 123</td>
<td>phone ###</td>
<td>Birthday</td>
<td>Other Data</td>
</tr>
<tr>
<td>John Smyth</td>
<td>I live here 456</td>
<td>phone ###</td>
<td>Birthday</td>
<td>Other Data</td>
</tr>
</table>
EOT
data = []
doc.at('table').search('tr').each do |tr|
data << tr.search('td').map(&:text)
end
pp data
Which outputs:
[["John Smith", "I live here 123", "phone ###", "Birthday", "Other Data"],
["John Smyth", "I live here 456", "phone ###", "Birthday", "Other Data"]]
The code uses at to locate the first <table>, then iterates over each <tr> using search. For each row, it iterates over the cells and extracts their text.
Nokogiri's at finds the first occurrence of something, and returns a Node. search finds all occurrences and returns a NodeSet, which acts like an array. I'm using CSS accessors, instead of XPath, for simplicity.
As a FYI:
File.open(DOC_URL_FILE, 'w'){|file| file.write all_data}
can be written more succinctly as:
File.write(DOC_URL_FILE, all_data)
I've been working on this problem for awhile. Can you give me any more help?
Sigh...
Did you read the CSV documents, especially the examples? What happens if, instead of defining data = [] we replace it with:
CSV.open("path/to/file.csv", "wb") do |data|
and wrap the loop with the CSV block, like:
CSV.open("path/to/file.csv", "wb") do |data|
doc.at('table').search('tr').each do |tr|
data << tr.search('td').map(&:text)
end
end
That's not tested, but it's really that simple. Go and fiddle with that.

Related

Mechanize Ruby Get Text Directly inside Tag

I have some html that looks something like this
<tr>
What I want
<b>
What I don't want
</b>
<tr>
The code to get the text is
my_row = page.search('tr').first
puts my_row.text
The issue with this is it will output What I wantWhat I don't Want.
How do I extract only the text directly within the tag selected and not the text in any child elements?
I think you could access the tr tag, then the b child tag and remove it, this way you get just the "main" tr content:
require 'nokogiri'
data = <<-HTML
<tr>
What I want
<b>
What I don't want
</b>
<tr>
HTML
doc = Nokogiri::HTML.parse(data)
tr = doc.css('tr')
tr.css('b').remove
p tr.text
# "\n What I want\n \n\n"
You could use String#strip to get a text free of line breaks.
You'll want to use something like Nokogiri for parsing HTML.
https://github.com/sparklemotion/nokogiri
require 'nokogiri'
html = "<tr>
What I want
<b>
What I don't want
</b>
<tr>"
doc = Nokogiri::HTML(html)
text = doc.search('tr').xpath('text()')
puts text.text # What I want
I use child/children for this:
doc.at('tr').child.text

How to iterate a table with watir when no html element has identifiers

I have an html table which has a table with unequal number of columns for each row. The table and cells/columns have no identifiers such as id, name, class etc. How do I iterate over such a table and print it in tabular form ? I am using ruby 1.8 for now.
Html -
<table>
<tr><td colspan="2">Student Info</td></tr>
<tr><td>Age:</td> <td>15</td></tr>
<tr><td>Home:</td> <td>251 Palm Avenue</td></tr>
<tr><td>City:</td> <td>New York</td></tr>
<tr><td colspan="2">Parent Info</td></tr>
<tr><td>Parent Phone:</td> <td>231-1234-123</td></tr>
<tr><td>More parent info</td> <td><a href="http://www.school.com>school</a><br></td></tr>
</table>
Ruby code -
require 'rubygems'
require 'watir-webdriver'
url = "url has tables with no identifiable attributes. Just a table tag"
browser = Watir::Browser.new :firefox
browser.goto url
browser.table.trs.each do |tr|
tr.each do |td|
puts td.to_s
end
end
Trace -
C:/ruby/lib/ruby/gems/1.8/gems/watir-webdriver-0.6.2/lib/watir-webdriver/elements/element.rb:553:in `method_missing': undefined method `each' for #<Watir::TableRow:0x517bf9c> (NoMethodError)
from tables.rb:10
from C:/ruby/lib/ruby/gems/1.8/gems/watir-webdriver-0.6.2/lib/watir-webdriver/element_collection.rb:29:in `each'
from C:/ruby/lib/ruby/gems/1.8/gems/watir-webdriver-0.6.2/lib/watir-webdriver/element_collection.rb:29:in `each'
from tables.rb:9
Just grab the table, and send it to a file (or variable) iterating over the rows and placing a tab between the elements
browser = Watir::Browser.new :firefox
browser.goto url
f = File.new('table.txt', 'w+')
t = browser.table
t.trs.each do |trd|
trd.tds.each do |td|
f.print "#{td.text}\t"
end
f.print "\n"
end
f.close
EDIT** in answer to the question in the comments:
Well, don't be hard on yourself, I don't think the documentation is beginner friendly. I had to extrapolate from what Justin_Ko said and the docs to see that was referenced by tr and the collection of was ref'd by trs. The thing to remember is that those collections, and most everything returned by the WATIR methods are objects, but they might no behave like you think. trs is an Enumerator, but it only returns objects, not the text of the row itself. Same with td. That's why I had to iterate through the collection of rows then iterate through each row's td objects, then call .text on that object. Think about WATIR this way, you can reference anything by a class or identifier, or as in this case just by HTML elements. browser reads everything in the page, from there you can target any element(s) using the WATIR methods.
The cheat sheet is very handy:
https://github.com/watir/watir/wiki/Cheat-Sheet

ruby selenium xpath td css

I am testing a webapp using Ruby and Selenium web-driver. I have not been able to examine the contents of a cell in the displayed webpage.
What I would like to get is the IP in the td.
<td class="multi_select_column"><input name="object_ids" type="checkbox"
value="adcf0467-2756-4c02-9edd-bb83c40b8685" /></td>
<td class="sortable normal_column">Core</td>
<td class="sortable nowrap-col normal_column">r1-c4-b4</td>
<td class="sortable anchor normal_column"><a href="/horizon/admin/instances
/adcf0467-2756-4c02-9edd-bb83c40b8685/detail" class="">pg-gtmpg--675</a></td>
<td class="sortable normal_column">column_name</td><td class="sortable normal_column">
<tr
<ul>
<li>172.25.1.12</li>
</ul>
I used the Firefox addon firepath to get the Xpath of the IP.
It gives "html/body/div[1]/div[2]/div[3]/form/table/tbody/tr[1]/td[6]/ul/li", which looks correct.
However I have not been able to display the IP.
Here is my test code;
#usr/bin/env ruby
#
# Sample Ruby script using the Selenium client API
#
require "rubygems"
require "selenium/client"
require "test/unit"
require "selenium/client"
begin
driver = Selenium::WebDriver.for(:remote, :url =>"http://dog.dog.jump.acme.com:4444/wd/hub")
driver.navigate.to "http://10.87.252.37/acme/auth/login/"
g_user_name = driver.find_element(:id, 'id_username')
g_user_name.send_keys("user")
g_user_name.submit
g_password = driver.find_element(:id, 'id_password')
g_password.send_keys("password")
g_password.submit
g_instance_1 = driver.find_element(:xpath, "html/body/div[1]/div[2]/div[3]/form/table/tbody/tr[1] /td[4]/a")
puts g_instance_1.text() <- here, I see the can see text
g_instance_2 = driver.find_elements(:xpath, "html/body/div[1]/div[2]/div[3]/form/table/tbody/tr[1] /td[6]/ul/li[1]")
puts g_instance_2
output is <Selenium::WebDriver::Element:0x000000023c1700
puts g_instance_2.inspect
output is :[#<Selenium::WebDriver::Element:0x22f3b7c6e7724d4a id="4">]
puts g_instance_2.class
Output: Array
puts g_instance_2.count
Output:1
When there is no /a in the td it doesn't seem to work.
I have tried puts g_instance_2.text, g_instance_2.text() and many others with no success.
I must be missing something obvious, but I am not seeing it
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux] on
Linux ubuntu 3.8.0-34-generic #49~precise1-Ubuntu
I decided to try a different apporach using the css selector instead of xpath.
When I insert the following css selector into the FirePath window the desired html section is selected.
g_instance_2 = driver.find_elements(:css, "table#instances tbody tr:nth-of-type(1) td:nth-of-type(6) ul li:nth-of-type(1)" )
The problem is the same as before, I dont seem to be able to access the contents of g_instance_2
I have tried;
puts g_instance_2
g_instance_22 = [g_instance_2]
puts g_instance_22
Both return;
#<Selenium::WebDriver::Element:0x000000028a6ba8>
#<Selenium::WebDriver::Element:0x000000028a6ba8>
How can I check the value returned from the remote web-server?
Would Python be a better choice to do this?
The HTML code fragment you are trying to test is not valid HTML. It might be worth filing a bug report for it.
With the given code, the following CSS selector retrieves the <a> you want:
[href^="/horizon/admin/instances"]
Translated into: any element that has the "href" attribute starting with "/horizon/admin/instances"
For XPATH this is the selector
("//a[contains(#href,'/horizon/admin/instances')]")
Same translation just an uglier syntax.
The problem was that I was not accessing the returned array properly.
puts g_instance_2[0].text()
works for css and xpath

How to create an array scraping HTML?

I have a Rake task set-up, and it works almost how I want it to.
I'm scraping information from a site and want to get all of the player ratings into an array, ordered by how they appear in the HTML. I have player_ratings and want to do exactly what I did with the player_names variable.
I only want the fourth <td> within a <tr> in the specified part of the doc because that corresponds to the ratings. If I use Nokogiri's text, I only get the first player rating when I really want an array of all of them.
task :update => :environment do
require "nokogiri"
require "open-uri"
team_ids = [7689, 7679, 7676, 7680]
player_names = []
for team_id in team_ids do
url = URI.encode("http://modules.ussquash.com/ssm/pages/leagues/Team_Information.asp?id=#{team_id}")
doc = Nokogiri::HTML(open(url))
player_names = doc.css('.table.table-bordered.table-striped.table-condensed')[1].css('tr td a').map(&:content)
player_ratings = doc.css('.table.table-bordered.table-striped.table-condensed')[1].css('tr td')[3]
puts player_ratings
player_names.map{|player| puts player}
end
end
Any advice on how to do this?
I think changing your xpath might help. Here is the xpath
nodes = doc.xpath "//table[#class='table table-bordered table-striped table-condensed'][2]//tr/td[4]"
data = nodes.each {|node| node.text }
Iterating the nodes with node.text gives me
4.682200 
5.439000 
5.568400 
5.133700 
4.480800 
4.368700 
2.768100 
3.814300 
5.103400 
4.567000 
5.103900 
3.804400 
3.737100 
4.742400 
I'd recommend using Wombat (https://github.com/felipecsl/wombat), where you can specify that you want to retrieve a list of elements matched by your css selector and it will do all the hard work for you
It's not well known, but Nokogiri implements some of jQuery's JavaScript extensions for searching using CSS selectors. In your case, the :eq(n) method will be useful:
require 'nokogiri'
doc = Nokogiri::XML(<<EOT)
<html>
<body>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
</body>
</html>
EOT
doc.at('td:eq(4)').text # => "4"

Best way to parse a table in Ruby

I'd like to parse a simple table into a Ruby data structure. The table looks like this:
alt text http://img232.imageshack.us/img232/446/picture5cls.png http://img232.imageshack.us/img232/446/picture5cls.png
Edit: Here is the HTML
and I'd like to parse it into an array of hashes. E.g.,:
schedule[0]['NEW HAVEN'] == '4:12AM'
schedule[0]['Travel Time In Minutes'] == '95'
Any thoughts on how to do this? Perl has HTML::TableExtract, which I think would do the job, but I can't find any similar library for Ruby.
You might like to try Hpricot (gem install hpricot, prepend the usual sudo for *nix systems)
I placed your HTML into input.html, then ran this:
require 'hpricot'
doc = Hpricot.XML(open('input.html'))
table = doc/:table
(table/:tr).each do |row|
(row/:td).each do |cell|
puts cell.inner_html
end
end
which, for the first row, gives me
<span class="black">12:17AM </span>
<span class="black">
</span>
<span class="black">1:22AM </span>
<span class="black">
</span>
<span class="black">65</span>
<span class="black">TRANSFER AT STAMFORD (AR 1:01AM & LV 1:05AM) </span>
<span class="black">
N
</span>
So already we're down to the content of the TD tags. A little more work and you're about there.
(BTW, the HTML looks a little malformed: you have <th> tags in <tbody>, which seems a bit perverse: <tbody> is fairly pointless if it's just going to be another level within <table>. It makes much more sense if your <tr><th>...</th></tr> stuff is in a separate <thead> section within the table. But it may not be "your" HTML, of course!)
In case there isn't a library to do that for ruby, here's some code to get you started writing this yourself:
require 'nokogiri'
doc=Nokogiri("<table><tr><th>la</th><th><b>lu</b></th></tr><tr><td>lala</td><td>lulu</td></tr><tr><td><b>lila</b></td><td>lolu</td></tr></table>")
header, *rest = (doc/"tr").map do |row|
row.children.map do |c|
c.text
end
end
header.map! do |str| str.to_sym end
item_struct = Struct.new(*header)
table = rest.map do |row|
item_struct.new(*row)
end
table[1].lu #=> "lolu"
This code is far from perfect, obviously, but it should get you started.

Resources