本文共 1260 字,大约阅读时间需要 4 分钟。
Python版本:3.X
IDE:jupyterurllib is a package that collects several modules for working with URLs:
urllib.request for opening and reading URLs urllib.error containing the exceptions raised by urllib.request urllib.parse for parsing URLs urllib.robotparser for parsing robots.txt files
翻译:
urllib是一个包含了多个模块用于收集url信息的一个包: 1.urllib.request模块是用来打开和读取URLs的; 2.urllib.error模块包含一些有urllib.request产生的错误,可以使用try进行捕捉处理; 3.urllib.parse模块包含了一些解析URLs的方法; 4.urllib.robotparser模块用来解析robots.txt文本文件。在python2.x的版本中,有urllib和urllib2两个包,分别起到不同的功能作用(不是版本进化的关系)
python 3.x中urllib库和urilib2库合并成了urllib库 其中 urllib2.urlopen()变成了urllib.request.urlopen() urllib2.Request()变成了urllib.request.Request()# -*- coding: UTF-8 -*-from urllib import requestif __name__ == "__main__": result= request.urlopen("http://www.baidu.com") html = result.read() print(html)
urllib使用使用request.urlopen()打开和读取url的信息,返回的对象result为一个对象,可以使用read()将内容读取,再通过print(),将读到的信息打印出来。如下图所示
可以看到上面打印出来的爬取到的存在编码与我们所需不符的情况
这个时候可以使用decode()进行解码
# -*- coding: UTF-8 -*-from urllib import requestif __name__ == "__main__": result= request.urlopen("http://www.baidu.com") html = result.read().decode() print(html)
效果如下图所示,表示已经成功爬取到了百度首页的内容。
我们也可以用正则表达式去精确获取我们所得到结果中的某一部分的内容,比如title等