# 使用Python Requests库获取HTTP数据指南

**URL:** <https://www.isharkfly.com/t/python-requests-http/16583>\
**Category:** 程序语言\
**Tags:** python\
**Created:** [November 7, 2024, 2:12am UTC](https://www.isharkfly.com/t/python-requests-http/16583 "2024-11-07T02:12:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![hex](https://www.isharkfly.com/user_avatar/www.isharkfly.com/hex/32/21953_2.png) [@hex](https://www.isharkfly.com/u/hex)\
**Post date:** [November 7, 2024, 2:12am UTC](https://www.isharkfly.com/t/python-requests-http/16583/1 "2024-11-07T02:12:48Z")

</div>

python requests 如何获得返回数据

* * *

可以访问：[Quickstart — Requests 2.33.1 documentation](https://requests.readthedocs.io/en/latest/user/quickstart/#response-content) 来打印返回数据。

 ![2024-11-06_21-15-07](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/a/a3786a7a28c4d8511397022c0a21a6a53018240a.png)

返回 Json 使用

```auto
req = requests.get(server, auth=('user',"pass"))
req.json()

```

如果需要文本的话，则使用：

```auto
req.text

```

---

<div class="post-metadata">

**Author:** ![hex](https://www.isharkfly.com/user_avatar/www.isharkfly.com/hex/32/21953_2.png) [@hex](https://www.isharkfly.com/u/hex)\
**Post date:** [November 7, 2024, 2:12am UTC](https://www.isharkfly.com/t/python-requests-http/16583/2 "2024-11-07T02:12:49Z")

</div>

在 Python 中，使用 `requests` 库可以方便地发送 HTTP 请求并获取返回的数据。下面是一个简要的教程，介绍如何使用 `requests` 库来获取返回的数据：

首先，确保你已经安装了 `requests` 库。如果没有安装，可以通过以下命令进行安装：

```bash
pip install requests

```

下面是一个简单的例子，演示如何发送一个 HTTP GET 请求并获取响应的数据：

```python
import requests

# 发送一个 GET 请求
response = requests.get('https://api.example.com/data')

# 检查请求是否成功
if response.status_code == 200:
    # 打印返回的 JSON 数据
    data = response.json() # 如果返回的数据是 JSON 格式
    print(data)
else:
    print(f"请求失败，状态码：{response.status_code}")

# 打印原始的文本内容
raw_data = response.text
print(raw_data)

```

### 代码说明：

- `requests.get(url)`：向指定的 URL 发送一个 GET 请求。
- `response.status_code`：返回 HTTP 状态码。200 表示请求成功。
- `response.json()`：将响应内容解析为 JSON 格式的数据（如果返回是 JSON 格式）。
- `response.text`：返回响应的原始文本数据。

你可以根据具体的 API 文档来处理不同格式的响应数据（如 XML、HTML 等）。根据需要，还可以使用 `requests.post()`、`requests.put()`、`requests.delete()` 等方法来发送不同类型的请求。

---

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [November 7, 2024, 2:13am UTC](https://www.isharkfly.com/t/python-requests-http/16583/3 "2024-11-07T02:13:15Z")

</div>


