- Python 3 爬虫、数据清洗与可视化实战(第2版)
- 零一
- 1245字
- 2025-02-20 23:38:48
2.3 使用requests库请求网站
2.3.1 安装requests库
首先在PyCharm中安装requests库,为此打开PyCharm,单击“File”(文件)菜单,选择“Default Settings”(默认设置)命令,如图2-6所示。

图2-6
在弹出的对话框中选择“Project Interpreter”(项目编译器)命令,确认当前选择的编译器,然后单击右上角的“+”按钮,如图2-7所示。
在搜索框中输入“requests”(注意,一定要输入完整,否则容易出错),勾选“Install to user’s site packages directory”(安装到用户的站点库目录)选项,如果不勾选该选项,则会安装在临时目录中;然后单击左下角的“Install Package”(安装库)按钮,如图2-8所示。

图2-7

图2-8
安装完成后,会在“Install Package”按钮上方显示“Package ‘requests’ installed successfully”(库的请求已成功安装),如图2-9所示;如果安装不成功,则会显示不成功的提示信息。

图2-9
2.3.2 爬虫的基本原理
1.网页请求的过程
(1)Request (请求)。
每个展示在用户面前的网页都必须经过这一步,也就是向服务器发送访问请求。
(2)Response(响应)。
服务器在接收到用户的请求后,会验证请求的有效性,然后向用户(客户端)发送响应的内容;客户端接收服务器响应的内容,将内容展示出来,这就是我们所熟悉的网页请求,如图2-10所示。

图2-10
2.网页请求的方式
(1)GET:最常见的方式,一般用于获取或查询资源信息,参数设置在URL中,其也是大多数网站使用的方式,只需一次发送和返回,响应速度快。
(2)POST:相比GET方式,POST方式通过request body传递参数,可发送请求的信息远大于GET方式。
所以,在写爬虫前要先确定向谁发送请求,用什么方式发送请求。
2.3.3 使用GET方式抓取数据
复制任意一条首页首条新闻的标题,在源码页面按【Ctrl+F】组合键调出搜索框,将标题粘贴到搜索框中,然后按【Enter】键。
如图2-11所示,标题可以在源码中搜索到,请求对象是www.******.cn,请求方式是GET(所有在源码中的数据请求方式都是GET)。

图2-11
确定好请求对象和方式后,在PyCharm中输入以下代码。

代码运行结果如图2-12所示。

图2-12
加载库使用的语句是import+库的名称。在上述过程中,加载requests库的语句是importrequests。
用GET方式获取数据需要调用requests库中的get方法,使用方法是在requests后输入英文点号(.),如下所示。

将获取到的数据保存到strhtml变量中,代码如下。

这时strhtml是一个URL对象,它代表整个网页,但此时只需要网页中的源码,下面的语句表示网页源码。

2.3.4 使用POST方式抓取数据
首先进入某翻译页面,然后按快捷键【F12】进入开发者模式,单击“Network”选项卡,此时内容为空,如图2-13所示。

图2-13
在翻译页面中输入“我爱中国”,单击“翻译”按钮,如图2-14所示。

图2-14
在开发者模式中,依次单击“Network”→“XHR”,找到翻译数据,如图2-15所示。

图2-15
单击“Headers”选项卡,发现请求数据的方式为POST,如图2-16所示。

图2-16
找到数据所在之处并且明确请求方式之后,接下来开始撰写爬虫。
首先,将Headers中的URL复制出来,并赋值给url,代码如下。

POST请求获取数据的方式不同于GET,GET可以通过URL传递参数,而POST参数则需要放在请求实体里。Form Data中的请求参数如图2-17所示,将其复制并构建一个新字典。

图2-17

接下来使用requests.post()方法请求表单数据,代码如下。

将字符串格式的数据转换成JSON格式的数据,并根据数据结构提取数据,将翻译结果打印出来,代码如下。

使用requests.post()方法抓取翻译结果的完整代码如下。
