Python urllib
Python urllib is a library for working with web page URLs and for fetching and processing web page content.
This article mainly introduces urllib in Python 3.
The urllib package contains the following modules:
- urllib.request - open and read URLs.
- urllib.error - contains the exceptions raised by urllib.request.
- urllib.parse - parse URLs.
- urllib.robotparser - parse robots.txt files.
urllib.request
urllib.request defines functions and classes for opening URLs, including authentication, redirects, browser cookies, etc.
urllib.request can simulate the process of a browser initiating a request.
We can use urllib.request's urlopen method to open a URL; the syntax is as follows:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
- url: The url address.
- data: Other data object sent to the server, None by default.
- timeout: Set the access timeout.
- cafile and capath: cafile is the CA certificate, capath is the path to the CA certificate; both are needed when using HTTPS.
- cadefault: Deprecated.
- context: An ssl.SSLContext object used to specify SSL settings.
The example is as follows:
Example
from
urllib
.
request
import
urlopen
myURL
=
urlopen
(
"https://www.runoob.com/"
)
(
myURL.
read
(
)
)
The code above uses urlopen to open a URL, then uses the read() function to get the HTML entity code of the page.
read() reads the entire page content; we can specify the length to read:
Example
from
urllib
.
request
import
urlopen
myURL
=
urlopen
(
"https://www.runoob.com/"
)
(
myURL.
read
(
300
)
)
Besides the read() function, there are two other functions for reading page content:
-
readline() - Read one line of the file
from urllib.request import urlopen
myURL = urlopen("https://www.runoob.com/") print(myURL.readline()) # read one line
-
readlines() - Read the entire file content; it assigns the content to a list variable.
from urllib.request import urlopen
myURL = urlopen("https://www.runoob.com/") lines = myURL.readlines() for line in lines: print(line)
When scraping web pages we often need to check whether a page is accessible. Here we can use the getcode() function to get the page status code: 200 means the page is normal, 404 means the page does not exist:
Example
import
urllib
.
request
myURL1
=
urllib
.
request
.
urlopen
(
"https://www.runoob.com/"
)
(
myURL1.
getcode
(
)
)
200
try
:
myURL2
=
urllib
.
request
.
urlopen
(
"https://www.runoob.com/no.html"
)
except
urllib
.
error
.
HTTPError
as
e:
if
e.
code
==
404
:
(
404
)
404
For more web page status codes, see:https://www.runoob.com/http/http-status-codes.html。
If you want to save the scraped page locally, you can use Python3 File write() Method functions as follows:
Example
from
urllib
.
request
import
urlopen
myURL
=
urlopen
(
"https://www.runoob.com/"
)
f
=
open
(
"runoob_urllib_test.html"
,
"wb"
)
content
=
myURL.
read
(
)
Read the web page content
f.
write
(
content
)
f.
close
(
)
Running the code above generates a runoob_urllib_test.html file locally containing the content of https://www.runoob.com/.
For more Python File handling, see:https://www.runoob.com/python3/python3-file-methods.html
。
URL encoding and decoding can use urllib.request.quote() The difference between urllib.request.unquote() method in the component:
Example
import
urllib
.
request
encode_url
=
urllib
.
request
.
quote
(
"https://www.runoob.com/"
)
Encoding
(
encode_url
)
unencode_url
=
urllib
.
request
.
unquote
(
encode_url
)
Decode
(
unencode_url
)
The output is:
https%3A//www.runoob.com/
https://www.runoob.com/
Simulate header information
When scraping web pages we usually need to simulate headers (web page header information), which requires the urllib.request.Request class:
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
- url: The url address.
- data: Other data object sent to the server, None by default.
- headers: HTTP request header information, in dictionary format.
- origin_req_host: The host address of the request, an IP or a domain name.
- unverifiable: This parameter is rarely used; it sets whether the page requires authentication, defaulting to False.
- method: The request method, such as GET, POST, DELETE, PUT, etc.
Example - py3_urllib_test.py file code
import
urllib
.
request
import
urllib
.
parse
url
=
'https://www.runoob.com/?s='
Runoob Tutorial search page
keyword
=
'Python Tutorial'
key_code
=
urllib
.
request
.
quote
(
keyword
)
Encode the request
url_all
=
url+key_code
header
=
{
'User-Agent'
:
'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
# header information
request
=
urllib
.
request
.
Request
(
url_all
,
headers
=
header
)
reponse
=
urllib
.
request
.
urlopen
(
request
)
.
read
(
)
fh
=
open
(
"./urllib_test_runoob_search.html"
,
"wb"
)
Write the file to the current directory
fh.
write
(
reponse
)
fh.
close
(
)
Running the Python code above generates a urllib_test_runoob_search.html file in the current directory. Open the urllib_test_runoob_search.html file (you can use a browser); its content is as follows:

For form POST data transfer, let's first create a form, with the code below; here I used PHP code to get the form data:
Example - py3_urllib_test.php file code:
Runoob Tutorial(runoob.com) urllib POST Test
Example
import
urllib
.
request
import
urllib
.
parse
url
=
'https://www.runoob.com/try/py3/py3_urllib_test.php'
Submit to the form page
data
=
{
'name'
:
'RUNOOB'
,
'tag'
:
'Runoob Tutorial'
}
Submit the data
header
=
{
'User-Agent'
:
'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
# header information
data
=
urllib
.
parse
.
urlencode
(
data
)
.
encode
(
'utf8'
)
Encode the parameters; for decoding use urllib.parse.urldecode
request
=
urllib
.
request
.
Request
(
url
,
data
,
header
)
Request handling
reponse
=
urllib
.
request
.
urlopen
(
request
)
.
read
(
)
Read the result
fh
=
open
(
"./urllib_test_post_runoob.html"
,
"wb"
)
Write the file to the current directory
fh.
write
(
reponse
)
fh.
close
(
)
Running the code above submits the form data to the py3_urllib_test.php file, and the output is written to the urllib_test_post_runoob.html file.
Open the urllib_test_post_runoob.html file (you can use a browser); the result displayed is as follows:

urllib.error
The urllib.error module defines exception classes for the exceptions raised by urllib.request; the base exception class is URLError.
urllib.error contains two methods, URLError and HTTPError.
URLError is a subclass of OSError, raised (or a derived exception is raised) when the program encounters a problem; its reason attribute gives the cause of the exception.
HTTPError is a subclass of URLError, used to handle specific HTTP errors such as authentication requests. Its attributes are code for the HTTP status code, reason for the cause of the exception, and headers for the HTTP response headers of the particular HTTP request that caused the HTTPError.
Scrape a page that does not exist and handle the exception:
Example
import
urllib
.
request
import
urllib
.
error
myURL1
=
urllib
.
request
.
urlopen
(
"https://www.runoob.com/"
)
(
myURL1.
getcode
(
)
)
200
try
:
myURL2
=
urllib
.
request
.
urlopen
(
"https://www.runoob.com/no.html"
)
except
urllib
.
error
.
HTTPError
as
e:
if
e.
code
==
404
:
(
404
)
404
urllib.parse
urllib.parse is used to parse URLs, with the following format:
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
urlstring is the url address as a string, scheme is the protocol type,
If the allow_fragments parameter is false, fragment identifiers cannot be recognized. Instead, they are parsed as part of the path, parameters or query component, and fragment is set to an empty string in the return value.
Example
from
urllib
.
parse
import
urlparse
o
=
urlparse
(
"https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B"
)
(
o
)
The output of the above example is:
ParseResult(scheme='https', netloc='www.runoob.com', path='/', params='', query='s=python+%E6%95%99%E7%A8%8B', fragment='')
As the result shows, the content is a tuple containing 6 strings: scheme, netloc, path, params, query, fragment.
We can read the scheme content directly:
Example
from
urllib
.
parse
import
urlparse
o
=
urlparse
(
"https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B"
)
(
o.
scheme
)
The output of the above example is:
https
The full content is as follows:
|
property |
Index |
Value |
Value (if it does not exist) |
|---|---|---|---|
|
|
0 |
URL scheme |
scheme Parameters |
|
|
1 |
Network location part |
Empty string |
|
|
2 |
Hierarchical path |
Empty string |
|
|
3 |
Parameters of the last path element |
Empty string |
|
|
4 |
Query component |
Empty string |
|
|
5 |
Fragment identifier |
Empty string |
|
|
Username |
|
|
|
|
Password |
|
|
|
|
Host name (lowercase) |
|
|
|
|
Port number as an integer (if present) |
|
urllib.robotparser
urllib.robotparser is used to parse robots.txt files.
robots.txt (all lowercase) is a robots protocol file placed in a website's root directory; it is usually used to tell search engines the site's crawling rules.
urllib.robotparser provides the RobotFileParser class, with the following syntax:
class urllib.robotparser.RobotFileParser(url='')
This class provides methods for reading and parsing robots.txt files:
-
set_url(url) - Set the URL of the robots.txt file.
-
read() - Read the robots.txt URL and feed it to the parser.
-
parse(lines) - Parse the lines argument.
-
can_fetch(useragent, url) - Return True if useragent is allowed to fetch url according to the rules in the parsed robots.txt file.
-
mtime() - Return the time the robots.txt file was last fetched. This is useful for long-running web crawlers that need to check periodically for updates to robots.txt.
-
modified() - Set the time the robots.txt file was last fetched to the current time.
-
crawl_delay(useragent) - Return the Crawl-delay parameter from robots.txt for the specified useragent. Returns None if the parameter does not exist or does not apply to the specified useragent, or if the robots.txt entry for the parameter has a syntax error.
-
request_rate(useragent) - Return the contents of the Request-rate parameter from robots.txt as a named tuple RequestRate(requests, seconds). Returns None if the parameter does not exist or does not apply to the specified useragent, or if the robots.txt entry for the parameter has a syntax error.
-
site_maps() - Return the contents of the Sitemap parameter from robots.txt as a list(). Returns None if the parameter does not exist or if the robots.txt entry for the parameter has a syntax error.
Example
import
urllib
.
robotparser
rp
=
urllib
.
robotparser
.
RobotFileParser
(
)
rp.
set_url
(
"http://www.musi-cal.com/robots.txt"
)
rp.
read
(
)
rrate
=
rp.
request_rate
(
"*"
)
rrate.
requests
3
rrate.
seconds
20
rp.
crawl_delay
(
"*"
)
6
rp.
can_fetch
(
"*"
,
"http://www.musi-cal.com/cgi-bin/search?city=San+Francisco"
)
False
rp.
can_fetch
(
"*"
,
"http://www.musi-cal.com/"
)
True