urllib的用法
介绍
- urllib 是 python3.X中提供的一系列操作URL的库,它可以轻松的模拟用户使用浏览器访问网页
使用步骤
-
导入 urllib 库的 request 模块
from urllib import request
-
请求 url
res = request.urlopen('www.baidu.com')
res的返回值是一个http对象
-
使用相应对象输出数据
print(res.read().decode('utf-8'))
此处的decode编码格式视html代码的<meta charset=''>而定
-
模拟一个真实的浏览器请求
- 携带 User-Agent 请求头信息
- 方法1:
req = request.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36') res = request.urlopen(req) print(res.read().decode('utf8'))
- 方法2:
header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36' } req = request.Requset(url=url, headers=header) res = request.urlopen(req) print(res.read().decode('utf8'))
- 方法1:
- 发送POST请求
- 导入 urllib 库下面的parse
from urllib import parse
- 使用 urlencode 生成 post 数据
post_data = { 'key1': value1, 'key2': value2, 'key3': value3 } post_data = parse.urlencode(post_data)
- 使用生成的数据发送 post 请求,注意数据要转码为 'utf8' 格式
res = request.urlopen(url, data=post_data.encode('utf-8'))
- 使用 read() 查看响应信息
print(res.read().decode('utf8'))
- 导入 urllib 库下面的parse
- 携带 User-Agent 请求头信息
网友评论