Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python urllib

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

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)

The example is as follows:

Example

from

urllib

.

request

import

urlopen

myURL

=

urlopen

(

"https://www.runoob.com/"

)

print

(

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/"

)

print

(

myURL.

read

(

300

)

)

Besides the read() function, there are two other functions for reading page content:

myURL = urlopen("https://www.runoob.com/") print(myURL.readline()) # read one line

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/"

)

print

(

myURL1.

getcode

(

)

)

 

200

try

:

    myURL2

=

urllib

.

request

.

urlopen

(

"https://www.runoob.com/no.html"

)

except

urllib

.

error

.

HTTPError

as

e:

   

if

e.

code

==

404

:

       

print

(

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

print

(

encode_url

)

unencode_url

=

urllib

.

request

.

unquote

(

encode_url

)

   

Decode

print

(

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)

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:

<p>Runoob Tutorial(runoob.com) urllib POST Test</p>

    Name:


    Tag:


   


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/"

)

print

(

myURL1.

getcode

(

)

)

 

200

try

:

    myURL2

=

urllib

.

request

.

urlopen

(

"https://www.runoob.com/no.html"

)

except

urllib

.

error

.

HTTPError

as

e:

   

if

e.

code

==

404

:

       

print

(

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"

)

print

(

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"

)

print

(

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)

scheme

0

URL scheme

scheme Parameters

netloc

1

Network location part

Empty string

path

2

Hierarchical path

Empty string

params

3

Parameters of the last path element

Empty string

query

4

Query component

Empty string

fragment

5

Fragment identifier

Empty string

username

Username

None

password

Password

None

hostname

Host name (lowercase)

None

port

Port number as an integer (if present)

None


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:

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