Creating a Weather Reporter
Let's now build a simple Weather Reporter application. The Weather data for any given location will be fetched from the network, suitably formatted and presented to the user.
We will use a higher-level module named urllib
to fetch Weather data from the web. The urllib
module is part of Python's standard library and it provides an easy to use API to work with URLs. It has four submodules:
urllib.request
– for opening and reading URLsurllib.error
– for handling exceptions raised byurllib.request
urllib.parse
– for parsing URLsurllib.robotparser
– for parsingrobots.txt
files
With urllib.request
, fetching the contents of a web page turns into a three-line code (see code 7.06_urllib_demo.py
):
import urllib.request with urllib.request.urlopen('http://www.packtpub.com/') as f: print(f.read())
This prints the entire HTML source code or whatever is the response from the web page http://www.packtpub.com. This is, in essence, the core of mining the web for data and information...