通过前几节课的学习,我们大概了解了通过urllib模块怎么样获取数据、解析数据、保存数据得到我们想要的数据了,今天呢,就给大家介绍一个Python爬虫获取数据的另外一个方法requests库。那么urllib和requests哪个好?urllib和requests有什么区别呢?
1.requests库怎么安装
我们已经讲解了Python内置的urllib模块,用于访问网络资源。但是,它用起来比较麻烦,而且,缺少很多实用的高级功能。
更好的方案是使用requests。它是一个Python第三方库,处理URL资源特别方便。
requests库的安装与安装其他第三方应用一样(如下图):


2.requests库怎么使用。
我们以简单的抓取百度网页(https://www.baidu.com/)为例进行操作:
第一步,导入requests库

第二步,发起请求。
首先我们需要判断请求类型。最常见的请求方式为 GET 和POST,我们可以通过右击检查-network-headers-Request Method可以看到该页面的请求方式为get

因此我们发起请求的格式为:
requests.get(网页地址)
第三步,获取网页内容。
首先我们需要判断我们获取到的网页是什么类型,同样可通过右击检查
-network-headers-Content-Type可以看到该网页的内容为text类型

因此我们获取网页的基本格式为:
response.text
如下图即可输出网页内容:

第四步,存储网页信息。
基本格式为:
with open(保存的文件名,读写模式,encoding="utf-8") as 变量:
变量.write(网页内容)

以上就是关于requests的用法,我们可以结合之前学过的内容,想想urllib与requests哪个更加方便,以及对于有反爬虫机制的网站,又应该如何用requests获取内容信息,下节课,我们对比一下urllib与requests的区别的是什么?以及urllib与requests哪种更好。