Python urllib和urllib2 库的用法

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请求、设置请求头等。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值