Python 爬虫与接口自动化必备Requests模块
import requests
# 定义一个函数来发送HTTP请求
def send_request(method, url, **kwargs):
try:
if method == 'GET':
response = requests.get(url, **kwargs)
elif method == 'POST':
response = requests.post(url, **kwargs)
elif method == 'PUT':
response = requests.put(url, **kwargs)
elif method == 'DELETE':
response = requests.delete(url, **kwargs)
elif method == 'PATCH':
response = requests.patch(url, **kwargs)
else:
raise ValueError('Unsupported HTTP method: ' + method)
# 打印请求的URL和响应状态码
print(f'{method} Request to {url} with status code: {response.status_code}')
# 返回响应对象
return response
except requests.exceptions.RequestException as e:
print(f'An error occurred: {e}')
return None
# 使用示例
url = 'https://api.example.com/data'
response = send_request('GET', url)
# 打印响应文本
if response is not None:
print(response.text)
这段代码定义了一个send_request
函数,它接受一个HTTP方法和URL,以及任何需要传递给requests
库的额外关键字参数。函数会根据传入的HTTP方法发送相应的请求,并打印出请求的URL和响应的状态码。如果请求成功,它还会返回响应对象;如果发生错误,它会捕获异常并返回None
。这个简单的函数可以作为编写爬虫或者调用API接口的基础,提高代码的模块化程度和可读性。
评论已关闭