Skip to content

Commit 5abb4c3

Browse files
committed
Initial commit.
0 parents  commit 5abb4c3

4 files changed

Lines changed: 611 additions & 0 deletions

File tree

‎LICENSE.mit‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2013 Brandon Amos <http://bamos.github.io>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Simple Python scripts.
2+
A collection of simple Python scripts.
3+
4+
## Listings
5+
+ [ScrapeCountries.py](http://bamos.github.io/2013/05/03/scraping-tables-python/) -
6+
Python 3.3 -
7+
Scraping HTML tables with HTMLParser.
8+
Tests using the [unittest](http://docs.python.org/3.3/library/unittest.html)
9+
framework are located in `ScrapeCountriesTest.py`.

‎ScrapeCountries.py‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
#!/usr/bin/env python3.3
2+
#
3+
# ScrapeCountries.py
4+
#
5+
# Scrapes countries from http://www.nationsonline.org
6+
#
7+
# Note: Because the website fluctuates, this is not up to date and
8+
# tests won't all pass. However, I'm leaving this for the HTMLParser
9+
# example rather than parsing accuracy.
10+
#
11+
# Brandon Amos
12+
# 2013.04.26
13+
14+
import argparse # Argument parsing.
15+
import html.parser # HTML parsing.
16+
import urllib.parse # URL retrieval.
17+
import urllib.request # URL retrieval.
18+
import re # Regular expressions.
19+
import pickle # Pickling.
20+
21+
# Given a URL, this retrieves the content with a utf8 encoding
22+
# and uses the CountryParser to extract the country names from
23+
# the tables.
24+
class URLParser():
25+
user_agent = ("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) "
26+
"AppleWebKit/525.13 (KHTML, like Gecko)"
27+
"Chrome/0.2.149.29 Safari/525.13")
28+
29+
def __init__(self, url, numCols, extractionMap, exceptions):
30+
# Request the html.
31+
request = urllib.request.Request(url)
32+
request.add_header("User-Agent",self.user_agent)
33+
try:
34+
response = urllib.request.urlopen(request)
35+
except:
36+
print("Error: Invalid URL. Exiting.")
37+
exit()
38+
htmlContent = response.read().decode("utf8")
39+
40+
# Some files have <br> in the middle of a <td> tag,
41+
# and cause the parser to misinterpret the data.
42+
htmlContent = htmlContent.replace("<br>", "")
43+
44+
# Parse the html.
45+
parser = CountryParser(numCols, extractionMap, exceptions, strict=False)
46+
htmlContent = parser.unescape(htmlContent) # Unescape HTML entities.
47+
parser.feed(htmlContent)
48+
parser.close()
49+
self.__countryData = parser.countryData
50+
51+
@property
52+
def countryData(self):
53+
return self.__countryData
54+
55+
# CountryParser keeps track of the HTML tags and appends country
56+
# names to a list.
57+
class CountryParser(html.parser.HTMLParser):
58+
59+
# Initialize the class variables.
60+
def __init__(self, numCols, extractionMap, exceptions, strict=False):
61+
super().__init__(strict=strict)
62+
63+
self.__numCols = numCols
64+
self.__extractionMap = extractionMap
65+
self.__exceptions = exceptions
66+
67+
# Maintain our position within tags.
68+
self.__in_tr = False
69+
self.__in_td = False
70+
71+
# Within rows specifically, keep track of our index.
72+
# This helps because we know the country name always
73+
# occurs in the 0th position, and if we've exceeded
74+
# `numCols` positions, then the current row does not have
75+
# the data we want.
76+
self.__td_position = 0
77+
78+
# Keep a record of possible data.
79+
self.__possible_data = []
80+
81+
# The country names, successfully parsed.
82+
self.__countryData = []
83+
84+
def handle_starttag(self, tag, attrs):
85+
if tag == "tr":
86+
self.__in_tr = True
87+
88+
# Reset the possible data.
89+
self.__td_position = 0
90+
self.__possible_data = []
91+
for i in range(self.__numCols):
92+
self.__possible_data.append("")
93+
elif tag == "td":
94+
self.__in_td = True
95+
96+
def handle_endtag(self, tag):
97+
if tag == "tr":
98+
self.__in_tr = False
99+
100+
if self.__td_position == self.__numCols:
101+
# Extract the columns and clean them up.
102+
extractedData = [self.__possible_data[i] for i in self.__extractionMap]
103+
for i in range(len(extractedData)):
104+
if extractedData[i]:
105+
extractedData[i] = extractedData[i].replace('\n', ' ').strip()
106+
107+
# Detect data with empty columns, unless it's an exception,
108+
# in which case we don't do this check.
109+
isIntersection = bool(set(extractedData) & set(self.__exceptions))
110+
if not isIntersection:
111+
for i in range(len(extractedData)):
112+
if not extractedData[i] or len(extractedData[i]) == 0:
113+
#print(extractedData)
114+
return
115+
116+
self.__countryData.append(extractedData)
117+
elif tag == "td":
118+
self.__in_td = False
119+
self.__td_position += 1
120+
121+
# If our criteria match, we know our position in the table.
122+
# Keep track of the data.
123+
def handle_data(self, data):
124+
if self.__in_tr:
125+
if self.__in_td:
126+
if self.__td_position < self.__numCols:
127+
self.__possible_data[self.__td_position] += data
128+
129+
@property
130+
def countryData(self):
131+
return self.__countryData
132+
133+
# Define usage when running this from the command line.
134+
if __name__ == '__main__':
135+
parser = argparse.ArgumentParser(
136+
description='Scrape countries from http://www.nationsonline.org.')
137+
parser.add_argument('url', type=str, help='The URL to scrape.')
138+
parser.add_argument('output', type=str, help='The output file.')
139+
parser.add_argument('-p', '--pickle', dest='p', action='store_true',
140+
help='Generate a pickle.')
141+
args = parser.parse_args()
142+
143+
genPickle = args.p
144+
url = args.url
145+
outputFile = args.output
146+
147+
# Default values.
148+
numPops = 0 # The number of irrelavant data values at the top to ignore.
149+
exceptions = [] # Legitamet country rows marked as erroneous.
150+
numCols = 3 # The number of columns.
151+
extractionMap = (0, 1, 2) # The subset of columns to use as output.
152+
153+
# Consider the different cases for each URL.
154+
baseUrl = ".*nationsonline.org/oneworld/"
155+
if re.match(baseUrl + "countrynames_arabic.htm", url):
156+
print("Parsing country names in Arabic.")
157+
numCols = 5
158+
extractionMap = (1, 2, 4)
159+
exceptions = ['Cayman Islands', 'Falkland Islands', 'Montenegro',
160+
'Saint Kitts and Nevis', 'Saint Vincent and the Grenadines',
161+
'Tokelau', 'Western Sahara']
162+
elif re.match(baseUrl + "country_names_in_chinese.htm", url):
163+
print("Parsing country names in Chinese.")
164+
numCols = 4
165+
extractionMap = (0, 1, 2, 3)
166+
exceptions = ['Tuvalu']
167+
numPops = 1
168+
elif re.match(baseUrl + "country_code_list.htm", url):
169+
print("Parsing country code list.")
170+
numCols = 5
171+
extractionMap = (1, 2, 3, 4)
172+
elif re.match(baseUrl + "countries_of_the_world.htm", url):
173+
print("Parsing countries of the world.")
174+
numCols = 5
175+
extractionMap = (1, 2, 3, 4)
176+
exceptions = ['Saint Kitts and Nevis',
177+
'Saint Vincent and the Grenadines', 'Virgin Islands (British)']
178+
elif re.match(baseUrl + "countrynames_german.htm", url):
179+
print("Parsing country names in German.")
180+
exceptions = ['Saint Kitts and Nevis',
181+
'Saint Vincent and the Grenadines',
182+
'South Georgia and South Sandwich Islands',
183+
'Virgin Islands (British)',
184+
'Western Sahara']
185+
elif re.match(baseUrl + "countrynames_italian.htm", url):
186+
print("Parsing country names in Italian.")
187+
exceptions = ['French Southern Territories',
188+
'Saint Kitts and Nevis',
189+
'Saint Vincent and the Grenadines',
190+
'South Georgia and South Sandwich Islands',
191+
'U.S. Minor Outlying Islands',
192+
'Virgin Islands (British)',
193+
'Western Sahara']
194+
elif re.match(baseUrl + "countrynames_russian.htm", url):
195+
print("Parsing country names in Russian.")
196+
exceptions = ['Saint Kitts and Nevis',
197+
'Saint Vincent and the Grenadines',
198+
'Western Sahara']
199+
elif re.match(baseUrl + "countrynames_spanish.htm", url):
200+
print("Parsing country names in Spanish.")
201+
numCols = 5
202+
extractionMap = (1, 2, 3, 4)
203+
exceptions = ['Saint Kitts and Nevis',
204+
'Saint Vincent and the Grenadines',
205+
'Virgin Islands (British)']
206+
else:
207+
print("Unrecognized url. Using default (and likely incorrect) values.")
208+
209+
print("Using {0} columns overall and extracting columns {1}.".format(
210+
numCols, extractionMap))
211+
212+
# Parse the HTML and pop the irrelevant values from the results.
213+
parsedURL = URLParser(url, numCols, extractionMap, exceptions)
214+
countryData = parsedURL.countryData
215+
for i in range(numPops):
216+
countryData.pop(0)
217+
218+
# Write the data to disk.
219+
if genPickle:
220+
f = open(args.output, 'wb')
221+
pickle.dump(countryData, f, pickle.HIGHEST_PROTOCOL)
222+
f.close()
223+
else:
224+
f = open(args.output, 'w', encoding="utf8")
225+
for country in countryData:
226+
f.write('\t'.join(map(str,country)))
227+
f.write('\n')
228+
f.close()
229+
print("Finished extracting. Data written to '{0}'".format(outputFile))

0 commit comments

Comments
 (0)