# Ruby screen scraping

**URL:** <https://rubytalk.org/t/ruby-screen-scraping/33068>\
**Category:** ruby-talk\
**Created:** [19 November 2006 16:17 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068 "2006-11-19T16:17:16Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chris\_Gallagher](https://avatars.discourse-cdn.com/v4/letter/c/ee59a6/32.png) [@Chris\_Gallagher](https://rubytalk.org/u/Chris_Gallagher)\
**Post date:** [19 November 2006 16:17 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/1 "2006-11-19T16:17:16Z")

</div>

Hi,

I'm looking at creating a ruby script that will firstly access our  
cruise control page on localhost and examin the page to see the values  
on the page, so basically telling us if the build succeeded or failed.

Does anyone have any opinions on what might be the best way to approach  
this task. Ive been looking at a number of different packages including  
Htree.

Thanks

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Marcelo\_Alvim](https://avatars.discourse-cdn.com/v4/letter/m/ba8739/32.png) [@Marcelo\_Alvim](https://rubytalk.org/u/Marcelo_Alvim)\
**Post date:** [19 November 2006 16:22 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/2 "2006-11-19T16:22:21Z")

</div>

Hi,

> **···**
>
> On 11/19/06, Chris Gallagher \<cgallagher@gmail.com\> wrote:
> 
> > I'm looking at creating a ruby script that will firstly access our  
> > cruise control page on localhost and examin the page to see the values  
> > on the page, so basically telling us if the build succeeded or failed.
> 
> If you want screen scraping, I would tell you to look at why's  
> excellent Hpricot HTML parser. It's really simple to use and very  
> effective.
> 
> [http://code.whytheluckystiff.net/hpricot/](http://code.whytheluckystiff.net/hpricot/)
> 
> Cheers,  
> Alvim.

---

<div class="post-metadata">

**Author:** ![Daniel\_Lucraft](https://avatars.discourse-cdn.com/v4/letter/d/a4c791/32.png) [@Daniel\_Lucraft](https://rubytalk.org/u/Daniel_Lucraft)\
**Post date:** [19 November 2006 16:27 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/3 "2006-11-19T16:27:35Z")

</div>

For HTML scraping I recommend scrAPI.

gem install scrapi

homepage:  
[http://blog.labnotes.org/category/scrapi/](http://blog.labnotes.org/category/scrapi/)

Example scraper:

Scraper.define do  
&nbsp;&nbsp;attr\_accessor :title, :author, :pub\_date, :content

&nbsp;&nbsp;process "div#GuardianArticle \> h1", :title =\> :text  
&nbsp;&nbsp;process "div#GuardianArticle \> font[size=2] \> b" do |element|  
&nbsp;&nbsp;&nbsp;&nbsp;@author = element.children[0].content  
&nbsp;&nbsp;&nbsp;&nbsp;@pub\_date = element.children[2].content.strip  
&nbsp;&nbsp;end  
&nbsp;&nbsp;process "div#GuardianArticleBody", :content =\> :text  
end

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Peter\_Szinek3](https://avatars.discourse-cdn.com/v4/letter/p/ea5d25/32.png) [@Peter\_Szinek3](https://rubytalk.org/u/Peter_Szinek3)\
**Post date:** [19 November 2006 16:43 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/4 "2006-11-19T16:43:35Z")

</div>

Chris Gallagher wrote:

> Hi,
> 
> I'm looking at creating a ruby script that will firstly access our  
> cruise control page on localhost and examin the page to see the values  
> on the page, so basically telling us if the build succeeded or failed.

Once you have the page (open-uri if you know the URL exactly, or  
www::mechanize if you need to navigate there (i.e. fill textfields,  
click buttons etc)) I recommend to check out these possibilities:

1) regular expressions  
2) HPpricot  
3) scrAPI  
4) Rubyful soup

Regular expressions would be the most old-school solution, in some cases  
such a wrapper is the most robust (but since you are in control of the  
generated page as I understood, robustness is possibly not an issue).

If you can't do it with regexps, HPricot will be most probably adequate  
(I would need to see the concrete page).

Finally, if neither of the above works, you should try scrAPI - and  
though I don't think so you should fail after this point, Rubyful soup  
is another possibility to check out.

Peter

> **···**
>
> \_\_  
> [http://www.rubyrailways.com](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![Jeff\_Barczewski](https://avatars.discourse-cdn.com/v4/letter/j/91b2a8/32.png) [@Jeff\_Barczewski](https://rubytalk.org/u/Jeff_Barczewski)\
**Post date:** [21 November 2006 05:26 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/5 "2006-11-21T05:26:14Z")

</div>

Chris,

There are many ways to accomplish this as others have pointed out. When I  
approached a similar task three years ago, I was working in the java world  
and would have loved to have some of the tools available for Ruby today.  
However I believe that the technique I used has merit in some situations  
today.

I was screen scraping realtor sites for data (to find the perfect house),  
because I was dissatisfied with the searching and data mining capabilities  
of the sites. I was mining multiple sites, so the technique had to be  
flexible but also resilient because I did not control the source sites (and  
they would often change their layout). My first attempt used xpath's to try  
and get to data, however that was futile since developers would often change  
the site's layout and even small changes would break the logic (ie. changing  
nesting of tables, or adding styling around data).

After taking a step back and considering the situation from a fresh  
perspective, I scrapped the idea of using xml style data location in  
something that seemed too fluid, too fragile.

My second approach was much more resilient, I used simple regular  
expressions to zoom in and find the data. After studying the source html I  
was able to discover a way to easily get to any data for the sites I was  
working on.

The basic approach was this:

1) I would use a regular expression to search into the html for something to  
get me close to the data, something that seemed to be consistent and  
unlikely to change. (a reference point)

2) I would then extract reasonable number of characters before and/or after  
the reference point based on where the data is located. It is not necessary  
to know exactly just gather a conservative amount beyond what you think you  
need.

3) repeat with step 1 if needed, or use regular expression to extract the  
data desired from this subsection of data extracted in step 2.

I wrapped these basic ideas in to a few simple methods to make it easy and  
it turned out to be a very successful approach. I found it easy to add new  
sites pretty easily and it turned out to be very robust technique that was  
very forgiving to changing fluff html. It was pretty easy to find a  
reference point in the html that was consistent, and once there the data was  
close by, so I'd extract a healthy chunk and then it was pretty easy to  
search in this smaller amount of data. Use logging for each step to help you  
while you are fine tuning the approach. But once I switched over to this  
approach, I never had to revisit the code once I set it up for a site, it  
just worked. Low tech, simple, but suprisingly effective.

Of course after many months of daily operation mining the realtor sites, I  
eventually found the perfect house and abandoned the code; it had served its  
purpose well. So I don't have anything concrete to offer you (and it was in  
Java), but if any of the other methods mentioned by the others don't quite  
meet your needs or end up being too fragile, you might consider a variation  
on this approach for your own data extraction. It is especially flexible for  
scraping sites which tend to vary over time. In your case it sounds like you  
have control over the source so many methods would work for you, however  
don't forget that there may be some variation over time if you ever upgrade  
(cruise control).

Hope it helps you or others that are pursuing this task!

Blessings,

Jeff Barczewski  
MasterView project developer, [http://masterview.org/](http://masterview.org/)  
Inspired Horizons Training and Consultancy [http://inspiredhorizons.com/](http://inspiredhorizons.com/)

> **···**
>
> On 11/19/06, Chris Gallagher \<cgallagher@gmail.com\> wrote:
> 
> > Hi,
> > 
> > I'm looking at creating a ruby script that will firstly access our  
> > cruise control page on localhost and examin the page to see the values  
> > on the page, so basically telling us if the build succeeded or failed.
> > 
> > Does anyone have any opinions on what might be the best way to approach  
> > this task. Ive been looking at a number of different packages including  
> > Htree.

---

<div class="post-metadata">

**Author:** ![Chris\_Gallagher](https://avatars.discourse-cdn.com/v4/letter/c/ee59a6/32.png) [@Chris\_Gallagher](https://rubytalk.org/u/Chris_Gallagher)\
**Post date:** [19 November 2006 16:40 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/6 "2006-11-19T16:40:40Z")

</div>

thanks guys I'll look into both of them.

Another question I would have is how would i then get this scraped info  
to insert into a mysql database called say "build" and a table called  
"results".

For now if you could base answers on the following htree code?

require 'open-uri'  
require 'htree'  
require 'rexml/document'

url = "[http://www.google.com/search?q=ruby](http://www.google.com/search?q=ruby)"  
open(url) {  
\>page\> page\_content = page.read()  
doc = HTree(page\_content).to\_rexml  
doc.root.each\_element('//a[@class="l"]') {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\>elem\> puts elem.attribute('href').value }  
}

which is returning a result of:

C:\\>ruby script2.rb  
[http://www.ruby-lang.org/](http://www.ruby-lang.org/)  
[http://www.ruby-lang.org/en/20020101.html](http://www.ruby-lang.org/en/20020101.html)

> **[Ruby on Rails](http://rubyonrails.org)**
>
> A web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern.

  
[http://www.rubycentral.com/](http://www.rubycentral.com/)  
[http://www.rubycentral.com/book/](http://www.rubycentral.com/book/)  

> **[Ruby (programming language)](https://en.wikipedia.org/wiki/Ruby_programming_language)**
>
> Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. According to its creator, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp. It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management.

  

> **[Ruby](https://en.wikipedia.org/wiki/Ruby)**
>
> A ruby is a pink to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Other varieties of gem-quality corundum are called sapphires. Ruby is one of the traditional cardinal gems, together with amethyst, sapphire, emerald, and diamond. The word ruby comes from ruber, Latin for red. The color of a ruby is due to the element chromium. The quality of a ruby is determined by its color, cut, and clarity, which, along with carat weight, affect its value. The brightest and m...

  
[http://www.w3.org/TR/ruby/](http://www.w3.org/TR/ruby/)  
[http://poignantguide.net/](http://poignantguide.net/)  
[http://www.zenspider.com/Languages/Ruby/QuickRef.html](http://www.zenspider.com/Languages/Ruby/QuickRef.html)

Cheers.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Peter\_Szinek3](https://avatars.discourse-cdn.com/v4/letter/p/ea5d25/32.png) [@Peter\_Szinek3](https://rubytalk.org/u/Peter_Szinek3)\
**Post date:** [19 November 2006 16:46 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/7 "2006-11-19T16:46:22Z")

</div>

Chris Gallagher wrote:

> thanks guys I'll look into both of them.
> 
> Another question I would have is how would i then get this scraped info  
> to insert into a mysql database called say "build" and a table called  
> "results".
> 
> For now if you could base answers on the following htree code?
> 
> require 'open-uri'  
> require 'htree'  
> require 'rexml/document'
> 
> url = "[ruby - Google Search](http://www.google.com/search?q=ruby&quot);  
> open(url) {  
> \>page\> page\_content = page.read()  
> doc = HTree(page\_content).to\_rexml  
> doc.root.each\_element('//a[@class="l"]') {  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\>elem\> puts elem.attribute('href').value }  
> }

Something along the lines of

require "mysql"

dbh = Mysql.real\_connect("localhost", "chris", "", "build")  
dbh.query("  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;INSERT INTO results  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VALUES (whatever)

Cheers,

Peter

> **···**
>
> \_\_  
> [http://www.rubyrailways.com](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![Chris\_Gallagher](https://avatars.discourse-cdn.com/v4/letter/c/ee59a6/32.png) [@Chris\_Gallagher](https://rubytalk.org/u/Chris_Gallagher)\
**Post date:** [19 November 2006 17:00 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/8 "2006-11-19T17:00:59Z")

</div>

Thanks for the help.

Ill get on with it and see how it goes 🙂

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Peter\_Szinek3](https://avatars.discourse-cdn.com/v4/letter/p/ea5d25/32.png) [@Peter\_Szinek3](https://rubytalk.org/u/Peter_Szinek3)\
**Post date:** [19 November 2006 17:10 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/9 "2006-11-19T17:10:37Z")

</div>

OK,here is the full code:

require 'open-uri'  
require 'htree'  
require 'rexml/document'  
require 'mysql'

url = "[http://www.google.com/search?q=ruby](http://www.google.com/search?q=ruby)"  
results = []

open(url) {  
\>page\> page\_content = page.read()  
doc = HTree(page\_content).to\_rexml  
doc.root.each\_element('//a[@class="l"]') {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\>elem\> results \<\< elem.attribute('href').value }

dbh = Mysql.real\_connect("localhost", "peter", "\*\*\*\*", "build")

results.each do |result|  
&nbsp;&nbsp;&nbsp;dbh.query("INSERT INTO result VALUES ('#{result}')")  
end  
}

HTH,

Peter

> **···**
>
> \_\_  
> [http://www.rubyrailways.com](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![Chris\_Gallagher](https://avatars.discourse-cdn.com/v4/letter/c/ee59a6/32.png) [@Chris\_Gallagher](https://rubytalk.org/u/Chris_Gallagher)\
**Post date:** [19 November 2006 17:20 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/10 "2006-11-19T17:20:27Z")

</div>

wow, thanks for that code.

One question though. Does the name of the field in the table which the  
scraped information is going to be inserted into need to be specified in  
the code? Or is it already and i'm missing something here?

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Peter\_Szinek3](https://avatars.discourse-cdn.com/v4/letter/p/ea5d25/32.png) [@Peter\_Szinek3](https://rubytalk.org/u/Peter_Szinek3)\
**Post date:** [19 November 2006 17:28 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/11 "2006-11-19T17:28:48Z")

</div>

Chris Gallagher wrote:

> wow, thanks for that code.

Welcome 🙂

> One question though. Does the name of the field in the table which the  
> scraped information is going to be inserted into need to be specified in  
> the code? Or is it already and i'm missing something here?

My code assumed that the table has one column (e.g. 'url' in this case)  
and the values were inserted into that column.

Otherwise if you have more columns, you can do this:

INSERT INTO people  
(name, age) VALUES('Peter Szinek', '23' ).

You can do

INSERT INTO people VALUES('Peter Szinek', '23' )

as well, but in this case you have to be sure that the columns in your  
DB are in the same order as in your insert query. In the first example  
you don't have to care about the column ordering in the DB, as far as  
the mapping between the column names (first pair of parens) and the  
values (second pair of parens) are O.K.

HTH,  
Peter

> **···**
>
> \_\_  
> [http://www.rubyrailways.com](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![Chris\_Gallagher](https://avatars.discourse-cdn.com/v4/letter/c/ee59a6/32.png) [@Chris\_Gallagher](https://rubytalk.org/u/Chris_Gallagher)\
**Post date:** [19 November 2006 17:53 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/12 "2006-11-19T17:53:25Z")

</div>

ah thats great.

thanks again for your help 🙂

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Chris\_Gallagher](https://avatars.discourse-cdn.com/v4/letter/c/ee59a6/32.png) [@Chris\_Gallagher](https://rubytalk.org/u/Chris_Gallagher)\
**Post date:** [19 November 2006 21:40 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/13 "2006-11-19T21:40:53Z")

</div>

OK that code all works great but i have one last question 🙂

This is allowing me to scrape the values of the class values on tags and  
any other attribues such as that. My question is, how would i modify the  
code in order to get it to capture say a block of text such as:

\<p\>this is text that i want to scrape\</p\>

any ideas?

thanks.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Peter\_Szinek3](https://avatars.discourse-cdn.com/v4/letter/p/ea5d25/32.png) [@Peter\_Szinek3](https://rubytalk.org/u/Peter_Szinek3)\
**Post date:** [19 November 2006 22:33 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/14 "2006-11-19T22:33:50Z")

</div>

Chris Gallagher wrote:

> OK that code all works great but i have one last question 🙂
> 
> This is allowing me to scrape the values of the class values on tags and  
> any other attribues such as that. My question is, how would i modify the  
> code in order to get it to capture say a block of text such as:
> 
> \<p\>this is text that i want to scrape\</p\>

Hmm this is hard to tell just by this example. If you need ALL \<p\>s,  
then those can be queried by this XPath:

//p

I am not sure what are you using now, but in Hpricot this would be:

doc = Hpricot(open("[http://stuff.com/&quot;\](http://stuff.com/&quot;%5C)))  
results = doc/"//p"

If you are still using, HTree, query this XPath there for the same results.

However, I guess you want something more sophisticated than ALL the  
\<p\>s. Well this is where the troubles begin with screen scraping: you  
need to figure out some rules which extract \*exactly\* what you want -  
usually it is not that hard to come up with rules that extract more or  
less, but much worse to find the right ones...

To solve this problem, you need to tell us what do you want - i.e. an  
example page, and a set of objects you would like to extract.

Cheers,  
Peter

> **···**
>
> \_\_  
> [http://www.rubyrailways.com](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![Paul\_Lutus](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@Paul\_Lutus](https://rubytalk.org/u/Paul_Lutus)\
**Post date:** [20 November 2006 02:50 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/15 "2006-11-20T02:50:08Z")

</div>

Chris Gallagher wrote:

> OK that code all works great but i have one last question 🙂
> 
> This is allowing me to scrape the values of the class values on tags and  
> any other attribues such as that. My question is, how would i modify the  
> code in order to get it to capture say a block of text such as:
> 
> \<p\>this is text that i want to scrape\</p\>
> 
> any ideas?

Really simple:

array = page\_content.scan(%r{\<p\>(.\*?)\</p\>}m).flatten

Returns an array, each cell of which is a paragraph from the original page.

This is why it is a bad idea to adopt a package or library to accomplish  
something that is easier to accomplish with a few lines of code, or even  
one line as in this case.

At first the library seems as though it can do anyting, with no need to  
understand what is actually going on. Pretty quickly you encounter  
something the library cannot do, and you have to ... understand what is  
going on. Then you abandon the library and write normal code.

In Ruby, writing normal code is so easy that the traditional cautions  
against adopting miraculous libraries should be amplified tenfold.

> **···**
>
> --  
> Paul Lutus  
> [http://www.arachnoid.com](http://www.arachnoid.com)

---

<div class="post-metadata">

**Author:** ![James\_Edward\_Gray\_II](https://avatars.discourse-cdn.com/v4/letter/j/ea5d25/32.png) [@James\_Edward\_Gray\_II](https://rubytalk.org/u/James_Edward_Gray_II)\
**Post date:** [20 November 2006 03:33 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/16 "2006-11-20T03:33:19Z")

</div>

I hope you're not arguing that HTML should be parsed with simple regular expression instead of a real parser. I think most would agree with me when I say that strategy seldom holds up for long.

James Edward Gray II

> **···**
>
> On Nov 19, 2006, at 8:50 PM, Paul Lutus wrote:
> 
> > Chris Gallagher wrote:
> > 
> > > OK that code all works great but i have one last question 🙂
> > > 
> > > This is allowing me to scrape the values of the class values on tags and  
> > > any other attribues such as that. My question is, how would i modify the  
> > > code in order to get it to capture say a block of text such as:
> > > 
> > > \<p\>this is text that i want to scrape\</p\>
> > > 
> > > any ideas?
> > 
> > Really simple:
> > 
> > array = page\_content.scan(%r{\<p\>(.\*?)\</p\>}m).flatten
> > 
> > Returns an array, each cell of which is a paragraph from the original page.
> > 
> > This is why it is a bad idea to adopt a package or library to accomplish  
> > something that is easier to accomplish with a few lines of code, or even  
> > one line as in this case.
> > 
> > At first the library seems as though it can do anyting, with no need to  
> > understand what is actually going on. Pretty quickly you encounter  
> > something the library cannot do, and you have to ... understand what is  
> > going on. Then you abandon the library and write normal code.
> > 
> > In Ruby, writing normal code is so easy that the traditional cautions  
> > against adopting miraculous libraries should be amplified tenfold.

---

<div class="post-metadata">

**Author:** ![Gabriele\_Marrone](https://avatars.discourse-cdn.com/v4/letter/g/6a8cbe/32.png) [@Gabriele\_Marrone](https://rubytalk.org/u/Gabriele_Marrone)\
**Post date:** [20 November 2006 13:10 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/17 "2006-11-20T13:10:52Z")

</div>

Please note that the P end tag isn't required in HTML 4.01:  
[http://www.w3.org/TR/html4/struct/text.html#h-9.3.1](http://www.w3.org/TR/html4/struct/text.html#h-9.3.1)

> **···**
>
> On 20/nov/06, at 03:50, Paul Lutus wrote:
> 
> > array = page\_content.scan(%r{\<p\>(.\*?)\</p\>}m).flatten
> 
> --  
> Gabriele Marrone

---

<div class="post-metadata">

**Author:** ![Paul\_Lutus](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@Paul\_Lutus](https://rubytalk.org/u/Paul_Lutus)\
**Post date:** [20 November 2006 08:45 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/18 "2006-11-20T08:45:09Z")

</div>

James Edward Gray II wrote:

> > Chris Gallagher wrote:
> > 
> > > OK that code all works great but i have one last question 🙂

/ ...

> > > > My question is, how would i modify the
> > > 
> > > code in order to get it to capture say a block of text such as:
> > > 
> > > \<p\>this is text that i want to scrape\</p\>
> > > 
> > > any ideas?
> > 
> > Really simple:
> > 
> > array = page\_content.scan(%r{\<p\>(.\*?)\</p\>}m).flatten
> > 
> > Returns an array, each cell of which is a paragraph from the  
> > original page.

/ ...

> > In Ruby, writing normal code is so easy that the traditional cautions  
> > against adopting miraculous libraries should be amplified tenfold.
> 
> I hope you're not arguing that HTML should be parsed with simple  
> regular expression instead of a real parser. I think most would  
> agree with me when I say that strategy seldom holds up for long.

That depends on the complexity of the problem to be solved, and the  
reliability of the source page's HTML formatting.

For a page that can pass validation of one kind or another or that is XHTML,  
the simplest kinds of parsers provide terrific results. For legacy pages  
and those that can be expected to have "relaxed" syntax, more robust  
parsers are required.

But I must say I regularly see requests here for parsers that can be  
expected to do anything, but often as not and IMHO, such a library  
represents too much complexity for the majority of routine HTML/XML parsing  
tasks with Web pages and documents that are often generated, not  
hand-written.

This thread is an example. Beginning with the generic equivalent of "Is  
there a library that can ..." followed almost immediately by "Great! But  
how do I make it do this ...", requesting a really trivial extraction step  
that can be accomplished in a single line of Ruby.

I find this rather ironic, since Ruby is meant to provide an easy way to  
create solutions to everyday problems. One then sees a blizzard of  
libraries whose purpose is to shield the user from the complexities of the  
language, in a way that the remedy is often more complex than the problem  
it is meant to solve.

In this thread, the OP started out by examining the alternatives among  
specialized libraries meant to address the general problem, but apparently  
never considered writing code to solve the problem directly. After choosing  
a library, the OP realized he didn't see an obvious way to solve the  
original problem -- extracting specific content from the source pages.

As to modern XHTML Web pages that can pass a validator, I know from direct  
recent experience that they yield to the simplest parser design, and can be  
relied on to produce a tree of organized content, stripped of tags and  
XHTML-specific formatting, in a handful of lines of Ruby code. It is hard  
to justify bringing out the big guns for a task like this, when one could  
instead use a small self-documenting routine such as I suggested.

In the bad old days of assembly and comparatively heavy, inflexible  
languages like C, C++ and the like, it is easy to see why people would be  
motivated to create specialized libraries to solve generic problems just  
once for all time. In fact, the argument can be made that Ruby is just such  
a library of generics, broadly speaking an extension/amplification of the  
STL project.

Now we see people writing easy-to-use application libraries, each composed  
using the easy-to-use Ruby library, but that are sometimes harder to sort  
out, or make practical use of, than a short bit of code would have been.

Lest my readers think I am going overboard here on a topic dear to my heart,  
let me quote the OP once again:

> > > OK that code all works great but i have one last question 🙂
> > > 
> > > This is allowing me to scrape the values of the class values on  
> > > tags and  
> > > any other attribues such as that. My question is, how would i  
> > > modify the  
> > > code in order to get it to capture say a block of text such as:
> > > 
> > > \<p\>this is text that i want to scrape\</p\>
> > > 
> > > any ideas?

In other words, after choosing a library and playing with it for a while, he  
found himself back in square one, unable to solve the original problem.

To quote one of my favorite authors (William Burroughs), it seems people are  
busy inventing cures for which there are no diseases.

> **···**
>
> > On Nov 19, 2006, at 8:50 PM, Paul Lutus wrote:
> 
> --  
> Paul Lutus  
> [http://www.arachnoid.com](http://www.arachnoid.com)

---

<div class="post-metadata">

**Author:** ![Peter\_Szinek3](https://avatars.discourse-cdn.com/v4/letter/p/ea5d25/32.png) [@Peter\_Szinek3](https://rubytalk.org/u/Peter_Szinek3)\
**Post date:** [20 November 2006 08:47 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/19 "2006-11-20T08:47:16Z")

</div>

Hola,

> > In Ruby, writing normal code is so easy that the traditional cautions  
> > against adopting miraculous libraries should be amplified tenfold.
> 
> I hope you're not arguing that HTML should be parsed with simple regular  
> expression instead of a real parser. I think most would agree with me  
> when I say that strategy seldom holds up for long.

I could not agree more with James here. HTML scraping is one of the most  
tedious tasks these days. Paul, how far would your scraper get with this  
'HTML':

\<p\>This is a para.  
\<b/\>  
\<p\>This is another...

With Hpricot, this code

equire 'rubygems'  
require 'hpricot'

doc = Hpricot(open("1.html").read)  
results = doc/"//p"

works without any problems.

Of course I absolutely understand your viewpoint, but messed up HTML, as  
you have seen, can make a real difference...

Peter

> **···**
>
> \_\_  
> [http://www.rubyrailways.com](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![Paul\_Lutus](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@Paul\_Lutus](https://rubytalk.org/u/Paul_Lutus)\
**Post date:** [20 November 2006 17:15 UTC](https://rubytalk.org/t/ruby-screen-scraping/33068/20 "2006-11-20T17:15:05Z")

</div>

Gabriele Marrone wrote:

> > array = page\_content.scan(%r{\<p\>(.\*?)\</p\>}m).flatten
> 
> Please note that the P end tag isn't required in HTML 4.01:  
> [Paragraphs, Lines, and Phrases](http://www.w3.org/TR/html4/struct/text.html#h-9.3.1)

Yes, I've just been converting all my site pages to XHTML, so I encountered  
this difference big-time. My solution made some assumptions, one being the  
OP's request --

> > My question is, how would i modify the  
> > code in order to get it to capture say a block of text such as:
> > 
> > \<p\>this is text that i want to scrape\</p\>
> > 
> > any ideas?

-- was based on his knowledge that the pages in fact contained paragraphs  
enclosed by \<p\> ... \</p\>.

The other assumption I made was based on context -- it seems the pages in  
question are machine-generated, so presumably can be relied on to have  
consistent syntax.

> **···**
>
> > On 20/nov/06, at 03:50, Paul Lutus wrote:
> 
> --  
> Paul Lutus  
> [http://www.arachnoid.com](http://www.arachnoid.com)

[Next page](https://rubytalk.org/t/ruby-screen-scraping/33068.md?page=2)
