Let’s assume we want to scrape the “Most Popular in News” box from bbc.com. What we need first is a CSS selector to locate what we are interested in. In this case it is simply a div tag with the ID “mostPopular” and you can figure this out using the Developer Tools of your favorite web browser. And now we are going to apply a chain of command line tools – each feeding their output to the next tool (that is called piping btw) and in the end we have a layouted text representation of the box’ content:
|
1
2
3
4
5
|
~>echo"http://www.bbc.com"|
wget-O--i-|
hxnormalize-x|
hxselect-i"div.most_popular_content"|
lynx-stdin-dump>theMostPoupularInNews
|
So let’s see what is going on. First the echo pipes the URL to wget. I could have also provided the URL directly in the arguments but I chose to do it like this to make clear that the URL or a list of URLs itself might be the result of processing. wget fetches the HTML code from BBC, which is then normalized by hxnormalize to improve digestability by hxselect (both installed on Ubuntu by sudo apt-get install html-xml-utils), which then extracts the part of the code being identified by the CSS selector. Lynx finally turns the code into a layouted text that you would see in a browser.
And this is what we get in the end:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
~>cattheMostPoupularInNews
[1]Shared
*[2]1Galileo satellites on wrong orbit
*[3]2UK imams condemn Isis inonline film
*[4]3Boy held for'killing pet dinosaur'
*[5]4Experts to review stroke clot-buster
[6]Read
*[7]1Merkel inUkraine as crisis mounts
*[8]2Galileo satellites on wrong orbit
*[9]3UN callto'prevent Iraq massacre'
*[10]4Many dead inMadrid plane crash
*[11]5Russian mother has'giant'baby
[12]Watched/Listened
*[13]1What are options infight against IS?
*[14]2Victoria Beckham does ice challenge
*[15]3SpaceX rocket explodes during testing
*[16]4Obama refuses ice bucket challenge
*[17]5'Wedding was saddest day of my life'
References
1.file:///tmp/lynxXXXXnXNyNy/L3209-8165TMP.html
2.http://www.bbc.co.uk/news/world-europe-28910662
3.http://www.bbc.co.uk/news/uk-28270296
4.http://www.bbc.co.uk/news/blogs-news-from-elsewhere-28897353
5.http://www.bbc.co.uk/news/health-28900824
6.file:///tmp/lynxXXXXnXNyNy/L3209-8165TMP.html
7.http://www.bbc.co.uk/news/world-europe-28910215
8.http://www.bbc.co.uk/news/world-europe-28910662
9.http://www.bbc.co.uk/news/world-middle-east-28910674
10.http://www.bbc.co.uk/2/hi/europe/7572643.stm
11.http://www.bbc.co.uk/2/hi/europe/7015841.stm
12.file:///tmp/lynxXXXXnXNyNy/L3209-8165TMP.html
13.http://www.bbc.co.uk/news/uk-28902128
14.http://www.bbc.co.uk/news/entertainment-arts-28896231
15.http://www.bbc.co.uk/news/world-us-canada-28910812
16.http://www.bbc.co.uk/news/world-us-canada-28892227
17.http://www.bbc.co.uk/news/world-middle-east-28315346
|
I love simple solutions and this is as simple as it can be (I guess).



