import requests
时间: 2024-08-14 21:10:11 浏览: 28
`requests` 是一个流行的 Python 库,用于发送 HTTP 请求并处理响应。它简化了与 Web 服务器的交互,使得编写网络爬虫、API 接口测试或其他涉及 HTTP 操作的脚本变得更加容易。
安装 `requests` 可以通过 pip 安装:
```bash
pip install requests
```
以下是使用 `requests` 发送 GET 和 POST 请求的基本示例:
1. 发送GET请求[^4]:
```python
import requests
response = requests.get('https://api.example.com/data')
data = response.json() # 假设返回的是 JSON 格式的数据
print(data)
```
2. 发送POST请求[^4] (包含JSON数据):
```python
import requests
import json
url = 'https://api.example.com/submit'
payload = {'key': 'value', 'another_key': 'another_value'}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
print(response.status_code)
```
相关问题
题目:编写一个爬取网页数据的函数,使用异常处理结构,输入一个网址发出访问请求,如网络畅通, web服务器能给出正确的响应,返回响应的字符,若不能正确下载网页数据,给出出错提示,返回空值。 注意:不可以增加或删除程序行,也不可以更改程序的结构。 import requests def get html( url, head): try: #**********FOUND* ********* r=requests. get(url, head=head, timeout=10) #**********FOUND******** r. status code #**********FOUND******** 1 r. encoding=utf-8 return r. text except: print("网页数据下载失败…") return None
import requests
def get_html(url, head):
try:
#**********FOUND* *********
r = requests.get(url, head=head, timeout=10)
#**********FOUND********
r.status_code
#**********FOUND********
r.encoding = 'utf-8'
return r.text
except requests.exceptions.RequestException as e:
print("网页数据下载失败…")
return None
headers:{ "content-type" : "text/plain" }
这是一个HTTP请求中的请求头,它指定了请求体中的数据内容的类型,这个例子中的类型是文本类型。具体来说,这个请求头的名称是“content-type”,它的值是“text/plain”[^1]。
在HTTP请求中,请求头是用来说明客户端想要做什么或者包含了什么信息,请求头还可以包含其他的元数据,比如使用的编码方式,可以接受的响应类型等等。请求头通常包含在HTTP请求的第一行中,然后是一些可选的请求头字段,每个字段都以名称和值的形式出现。这就允许更好的控制和管理客户端和服务端之间的通信[^2]。
在Python的requests库中,你可以使用headers参数来指定请求头,例如:
```python
import requests
url = 'http://www.example.com'
headers = {'content-type': 'text/plain'}
response = requests.get(url, headers=headers)
```
这个例子中,我们使用GET方法向URL为http://www.example.com的服务端发送请求,并且指定请求头为“content-type: text/plain”[^3]。