python requests的基本使用

简介: 使用python的requests库快速发起http请求,获取采集数据。

一、安装

  • pip快速安装
pipinstallrequests

二、使用方法

1)导入模块

importrequests

2)发送请求

  • 示例get请求:以百度搜索get请求为例
importrequests# 参数直接拼接到url的get请求r1=requests.get('https://www.baidu.com/s?wd=hello%20world')   
# 参数放到params的get请求(两种get请求方法最终发送的url都是https://www.baidu.com/s?wd=hello%20world)r2=requests.get(url='https://www.baidu.com/s', params={'wd': 'hello%20world'})
  • 常用请求方式
# GET请求requests.get('https://code_space/get') 
# POST请求requests.post('https://code_space/post')  
# PUT请求requests.put('https://code_space/put')
# DELETE请求requests.delete('https://code_space/delete')

3)定制头和cookie信息

cookie= {'key': 'value'}
header= {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Type": "application/json",
"Host": "ug.baidu.com",
"Origin": "https://www.baidu.com",
"Referer": "https://www.baidu.com/s?ie=UTF-8&wd=hello%20world",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"}
r=requests.get('https://www.baidu.com/s?wd=hello%20world',headers=header,cookies=cookie)

4)获取响应

r.encoding                     # 获取当前的编码
r.encoding = 'utf-8'       # 设置编码
r.text                              # 以encoding解析返回内容。字符串方式的响应体,会自动根据响应头部的字符编码进行解码。
r.content                        # 以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。
r.headers                       # 以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
r.status_code                 # 响应状态码
r.raw                              # 返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read()   
r.ok                               # 查看r.ok的布尔值便可以知道是否登陆成功
 #*特殊方法*#
r.json()                          #Requests中内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
r.raise_for_status()        #失败请求(非200响应)抛出异常
  • 使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……
  • 获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码。

三、测试demo

# -*- coding: utf-8 -*-"""@Time : 2022/1/16 16:15@Auth : 技术空间@File :requests_demo.py@IDE :PyCharm@Motto:技术总是要日积月累的"""importrequestsif__name__=='__main__':
r1=requests.get('https://www.baidu.com/s?wd=hello%20world')
cookie= {'key': 'value'}
header= {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Type": "application/json",
"Host": "ug.baidu.com",
"Origin": "https://www.baidu.com",
"Referer": "https://www.baidu.com/s?ie=UTF-8&wd=hello%20world",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"    }
r2=requests.get('https://www.baidu.com/s?wd=hello%20world', headers=header, cookies=cookie)
print("r1的status_code-->"+str(r1.status_code))
print(r1.text)
print("r2的status_code-->"+str(r1.status_code))
print(r2.text)

34b879fd8a3b47e2b66afa3aaa843eb2.pngb5b39dbd454144cb9eb430b3446a4ea2.png

相关文章
|
2天前
|
数据采集 存储 API
Python 网络请求:深入理解Requests库
Python 网络请求:深入理解Requests库
58 0
|
2天前
|
JSON 数据格式 Python
Python 的 requests 库是一个强大的 HTTP 客户端库,用于发送各种类型的 HTTP 请求
【5月更文挑战第9天】`requests` 库是 Python 中用于HTTP请求的强大工具。要开始使用,需通过 `pip install requests` 进行安装。发送GET请求可使用 `requests.get(url)`,而POST请求则需结合 `json.dumps(data)` 以JSON格式发送数据。PUT和DELETE请求类似,分别调用 `requests.put()` 和 `requests.delete()`。
28 2
|
2天前
|
JSON 数据格式 开发者
pip和requests在Python编程中各自扮演着不同的角色
【5月更文挑战第9天】`pip`是Python的包管理器,用于安装、升级和管理PyPI上的包;`requests`是一个HTTP库,简化了HTTP通信,支持各种HTTP请求类型及数据交互。两者在Python环境中分别负责包管理和网络请求。
31 5
|
2天前
|
数据采集 JSON API
如何用Python Requests发送请求
如何用Python Requests发送请求
10 0
|
2天前
|
存储 Python
Python网络数据抓取(3):Requests
Python网络数据抓取(3):Requests
16 5
|
2天前
|
数据采集 存储 JSON
Python爬虫面试:requests、BeautifulSoup与Scrapy详解
【4月更文挑战第19天】本文聚焦于Python爬虫面试中的核心库——requests、BeautifulSoup和Scrapy。讲解了它们的常见问题、易错点及应对策略。对于requests,强调了异常处理、代理设置和请求重试;BeautifulSoup部分提到选择器使用、动态内容处理和解析效率优化;而Scrapy则关注项目架构、数据存储和分布式爬虫。通过实例代码,帮助读者深化理解并提升面试表现。
25 0
|
2天前
|
Python
使用Python的Requests库进行网络请求和抓取网页数据
【4月更文挑战第20天】使用Python Requests库进行网络请求和网页数据抓取的步骤包括:安装库(`pip install requests`)、导入库、发送GET/POST请求、检查响应状态码、解析内容、处理Cookies、设置请求头以及异常处理。通过`response`对象访问响应信息,如`status_code`、`text`、`content`和`cookies`。可设置`headers`模拟用户代理,用`try-except`处理异常。
22 7
|
2天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
2天前
|
Python
如何使用Python的Requests库进行网络请求和抓取网页数据?
【4月更文挑战第19天】使用Python Requests库进行网络请求和网页数据抓取:安装库,导入requests,发送GET/POST请求,检查状态码(如`status_code==200`表示成功),解析响应内容(如`response.text`),处理Cookies和请求头,以及用try-except捕获异常。更多功能可深入学习Requests库。
12 2
|
2天前
|
JSON 网络安全 数据安全/隐私保护
「Python系列」Python requests模块
`requests` 是一个用 Python 语言编写的,用于发送 HTTP 请求的库。它使得发送 HTTP 请求变得简单,无需手动添加查询字符串到你的 URL 中,或者手动处理表单的编码。`requests` 会自动为你处理这些事情。
24 0