Customizing requests
To make use of the functionality that headers provide, we add headers to a request before sending it. To do this, we can't just use urlopen()
. We need to follow these steps:
Create a
Request
objectAdd headers to the request object
Use
urlopen()
to send the request object
We're going to learn how to customize a request for retrieving a Swedish version of the Debian home page. We will use the Accept-Language
header, which tells the server our preferred language for the resource it returns. Note that not all servers hold versions of resources in multiple languages, so not all servers will respond to Accept-Language
Linux home page.
First, we create a Request
object:
>>> from urllib.request import Request >>> req = Request('http://www.debian.org')
Next we add the header:
>>> req.add_header('Accept-Language', 'sv')
The add_header()
method takes the name of the header and the contents of the header as arguments. The Accept-Language
header takes two-letter...