Python urllib


Python urllib是Python内置的HTTP客户端库,它可以向Web服务器发送HTTP请求并接收响应。urllib库包含四个模块:urllib.request、urllib.parse、urllib.error和urllib.robotparser,每个模块都有自己的功能。

urllib.request模块是最常用的模块,它支持HTTP、HTTPS、FTP和文件等协议。该模块可以使用get和post方法发送请求,在请求时可以添加请求头信息。使用get方法发送请求:

import urllib.request
 
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

使用post方法发送请求:

import urllib.parse
import urllib.request
 
data = urllib.parse.urlencode({'name': 'jack', 'age': 20})
data = data.encode('utf-8')
response = urllib.request.urlopen('http://www.example.com', data)
print(response.read().decode('utf-8'))

urllib.parse模块用于URL的解析和操作,该模块提供了urlparse、urlunparse、urlsplit、urlunsplit、urljoin和urlencode等方法。使用urlparse解析URL:

from urllib.parse import urlparse
 
result = urlparse('http://www.example.com/index.html;user?id=5#comment')
print(result)

urllib.error模块包含了由urllib.request生成的异常,如果访问URL时出现HTTP错误,会抛出HTTPError异常。如果访问时出现其他错误,会抛出URLError异常。捕获HTTP异常:

from urllib import request,error
 
try:
    response = urllib.request.urlopen('http://www.example.com')
except urllib.error.HTTPError as e:
    print(e.code, e.reason)
except urllib.error.URLError as e:
    print(e.reason)
else:
    print('Request Successfully')

urllib.robotparser模块可以解析robots.txt文件,该文件用于限制爬虫程序访问某些网站的某些页面。解析robots.txt文件:

from urllib.robotparser import RobotFileParser
 
rp = RobotFileParser()
rp.set_url('http://www.example.com/robots.txt')
rp.read()
print(rp.can_fetch('*', 'http://www.example.com/index.html'))

使用Python的urllib库可以方便的对URL进行操作,实现HTTP请求的发送和解析,是Web爬虫、网站测试和数据分析等领域的重要组件。