龙听期货论坛's Archiver

龙听 发表于 2024-1-8 11:06

【Python工具包/库推荐系列】- requests

编写发送HTTP请求的代码可能很棘手,这在很大程度上要归因于HTTP并未以人类易于阅读的方式精确地格式化数据。

Requests Python程序包(座右铭:“ HTTP for Humans”)通过自动执行许多繁琐的任务来解决此问题,让发送HTTP请求变得异常简单。它消除了添加查询字符串或执行POST表单编码的需要。它还可以使与HTTP服务器的连接自动保持活动状态,从而无需编写大量代码。[code]
import requests
from requests.exceptions import HTTPError

for url in ['https://api.github.com', 'https://api.github.com/invalid']:
    try:
        response = requests.get(url)

        # If the response was successful, no Exception will be raised
        response.raise_for_status()
    except HTTPError as http_err:
        print(f'HTTP error occurred: {http_err}')  # Python 3.6
    except Exception as err:
        print(f'Other error occurred: {err}')  # Python 3.6
    else:
        print('Success!')
[/code]简而言之,如果您的应用程序通过HTTP发送任何数据,则请求是必不可少的程序包。

页: [1]