urllib包含模块
- urllib.request: 打开和读取URL
- urllib.error: 包含 urllib.request 产生的错误,使用 try 捕捉
- urllib.parse: 包含解析 URL 的方法
- urllib.robotparse: 解析 robots.txt 文件
案例 v1
from urllib import request
# 使用 urllib.request 请求一个网页内容,并打印出来
urls = "https://blog.csdn.net/xidianliutingting/article/details/53580569"
# 打开相应 URL 并把相应页面作为返回
rsp = request.urlopen(urls)
# 把返回结果读取出来
# 读取出来的内容为 bytes
html = rsp.read()
# 如果想把 bytes 内容转换成字符串,需要转码
htm = html.decode()
print(htm)
- 网页编码问题解决方案
- chardet 可以自动检测页面文件的编码格式,但可能有误
- 第三方包需要自行安装 pip install chardet
- 如果使用 anaconda 需要使用 conda install chardet
案例 v2
"""
利用 request 下载页面
自动检测页面编码
"""
import chardet
from urllib import request
urls = "http://stock.eastmoney.com/news/1407,20180616889634253.html"
rsp = request.urlopen(urls)
html = rsp.read()
# 利用 chardet 自动检测
cs = chardet.detect(html)
htm = html.decode(cs.get("encoding", "UTF-8"))
print(htm)