urllib和urllib2 库的用法

119 阅读1分钟

Python中的urllib和urllib2库是用于处理URL的标准库。它们提供了一些方法来处理URL,如打开URL、读取URL内容、发送POST和GET请求等。

以下是urllib和urllib2库的用法:

  1. urllib库

urllib库包含四个模块:urllib.request、urllib.parse、urllib.error和urllib.robotparser。

  • urllib.request模块

该模块提供了打开URL的方法,如urlopen()。可以使用该方法打开一个URL并读取其内容。

import urllib.request

response = urllib.request.urlopen('http://www.example.com')
html = response.read()
print(html)
  • urllib.parse模块

该模块提供了一些方法来处理URL,如解析URL、构建URL等。

import urllib.parse

url = 'http://www.example.com/search?q=python'
params = {'q': 'python'}
url_encoded = urllib.parse.urlencode(params)
print(url_encoded)
  • urllib.error模块

该模块提供了处理URL错误的方法。

import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://www.example.com')
except urllib.error.URLError as e:
    print(e.reason)
  • urllib.robotparser模块

该模块提供了一个类来解析robots.txt文件。

import urllib.robotparser

rp = urllib.robotparser.RobotFileParser()
rp.set_url('http://www.example.com/robots.txt')
rp.read()
print(rp.can_fetch('mybot', 'http://www.example.com'))
  1. urllib2库

urllib2库是urllib库的增强版,提供了更多的功能和更好的错误处理。

import urllib2

response = urllib2.urlopen('http://www.example.com')
html = response.read()
print(html)

urllib2库还提供了更多的方法,如发送POST和GET请求、设置请求头等。

2755a956f8556844ec36f888c22fd48.png