Python 爬虫02 urllib模块

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)
  • 网页编码问题解决方案
    1. chardet 可以自动检测页面文件的编码格式,但可能有误
    2. 第三方包需要自行安装 pip install chardet
    3. 如果使用 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值