Python爬虫——Requests 库基本使用

116 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第31天,点击查看活动详情

1、Requests简介和下载

Requests 库简介

在这里插入图片描述

Requests 库是在 urllib 模块的基础上开发而来,继承了urllib.request的所有特性。

Requests 采用了 Apache2 Licensed(一种开源协议)的 HTTP 库,支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的URL和POST数据自动编码。

与urllib.request 相比,Requests 在使用时更加简洁方便、快捷,所以 Requests 库在编写爬虫程序时使用较多。

官方文档对 Requests 库的介绍:比较生动形象

Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。
警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、
甚至死亡。

requests中文文档

Requests的下载安装

1、requests库安装位置:Python安装目录的Scripts文件夹下

2、安装命令:pip install requests-i pypi.douban.com/simple, 如下图则安装成功:

在这里插入图片描述

2、Requests 库基本使用

Requests 响应对象类型

这里分别使用 requests 和 urllib.request 向网站发起get请求,然后打印响应对象的型:

# 导入模块
import urllib.request
import requests

url = "https://www.baidu.com"

# requests 和 urllib.request 响应对象类型对比
# equests 发送get请求
response_s = requests.get(url=url)
# 打印响应对象:Response
print(type(response_s))

# urllib.request发送get请求
response = urllib.request.urlopen(url=url)
# 打印响应对象:HTTPResponse
print(type(response))

执行结果:可以看到,requests 的响应对象类型就是 Response,而urllib.request 的响应对象类型是 HTTPResponse

<class 'requests.models.Response'>
<class 'http.client.HTTPResponse'>

Requests 六个属性

requests 的响应对象类型是 Response,该Response对象具有以下几个常用属性:

常用属性说明
encoding返回或者指定响应对象的字符编码
status_code返回响应对象的HTTP响应码
url返回请求的 url 地址
headers返回请求头信息
cookies返回 cookies 信息
text以字符串形式返回网页源码
content以二进制数据形式返回网页源码,在保存下载图片时可以使用该属性

Response对象属性使用实例

代码实例:

import urllib.request
import requests

url = "https://www.baidu.com"
response_s = requests.get(url=url)


# 打印响应对象字符编码
print(response_s.encoding)

# 指定响应对象字符编码为utf-8
response_s.encoding="utf-8"

# 打印状态码
print(response_s.status_code)

# 打印请求url
print(response_s.url)

# 打印头信息
print(response_s.headers)

# 打印cookie信息
print(response_s.cookies)

# 以字符串形式打印网页源码
print(response_s.text)

# 以二进制数据形式打印网页源码
print(response_s.content)

执行结果:(网页源码省略)

# 响应对象字符编码
ISO-8859-1

# 状态码
200

# url 地址
https://www.baidu.com/

# 响应头信息
{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Fri, 19 Aug 2022 01:27:47 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:55 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

# cookie信息
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>