urllib库包含4个模块:
- request:模拟发送请求。像在浏览器里输入网址然后回车一样,只需要给库传入URL以及额外的参数,就可以模拟实现这个过程了。
- error:异常处理模块。
- parse:一个工具模块,提供许多URL处理办法,比如:拆分、解析、合并等。
- robotparser:识别网站的robots.txt文件,判断哪些网站可以爬,哪些不可以爬。
1. 发送请求
urllib.request模块提供了最基本的构造HTTP请求的方法。利用它可以模拟浏览器的一个请求发起过程。
1.1 urlopen()
以爬取Python官网为例:
import urllib.request
response = urllib.request.urlopen("https://www.python.org/")
html = response.read().decode('utf-8')
print(html)
运行结果如图:
我们用这几行代码就得到了想要抓取网页的源代码,之后,我们想要的链接、图片地址、文本信息就都可以提取出来了。
我们得到的响应类型是HTTPResponse,主要包含read()、readinto()、getheader(name)、getheaders()、fileno()等方法,以及msg、version、status、reason、debuglevel、closed**等属性。
得到这个对象后,把它赋值给response变量,然后就可以调用这些方法和属性,得到返回结果的一系列信息了。
实例:
import urllib.request
response = urllib.request.urlopen("https://www.python.org/")
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
输出结果:
200
[('Connection', 'close'), ('Content-Length', '49846'), ('Server', 'nginx'),
('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'DENY'),
('Via', '1.1 vegur, 1.1 varnish, 1.1 varnish'), ('Accept-Ranges', 'bytes'),
('Date', 'Tue, 13 Apr 2021 02:57:03 GMT'), ('Age', '83'),
('X-Served-By', 'cache-bwi5183-BWI, cache-hkg17933-HKG'),
('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '4, 196'),
('X-Timer', 'S1618282623.321738,VS0,VE0'), ('Vary', 'Cookie'),
('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx
可见,前两个输出了response的状态码和响应的头部信息,最后一个通过调用了getheader(),并传入参数Server获取了头部信息中的Server值,结果是nginx,意思是服务器是用nginx搭建的。
利用urlopen()方法可以完成最基本的简单网页的GET请求抓取。还可以通过urlopen()方法给链接传递一些参数,那么能传递哪些参数呢?看一下urlopen
()函数的API:
urllib.request.urlopen(url, data=None,[ timeout,] *, cafile=None, capath=None, cadefault=False, context=None