python requests下载
时间: 2023-11-03 12:56:23 浏览: 36
你可以使用Python中的requests库下载文件或网页。请参考以下示例代码:
```python
import requests
url = 'https://www.example.com/file.zip'
response = requests.get(url)
with open('filename.zip', 'wb') as f:
f.write(response.content)
```
在这个示例中,我们使用requests.get()方法来获取文件或网页的内容。然后,我们将内容写入一个文件中,使用'wb'参数,以确保二进制模式写入文件。
当然,您可以根据您想要下载的内容进行调整。希望这可以回答您的问题!
相关问题
python requests 下载
Python的requests库可以用来下载文件。具体步骤如下:
1. 导入requests库
```python
import requests
```
2. 发送请求并获取响应
```python
url = 'http://example.com/file.zip'
response = requests.get(url)
```
3. 将响应内容写入文件
```python
with open('file.zip', 'wb') as f:
f.write(response.content)
```
其中,'wb'表示以二进制写入模式打开文件,可以保证下载的文件不会出现乱码。
完整代码如下:
```python
import requests
url = 'http://example.com/file.zip'
response = requests.get(url)
with open('file.zip', 'wb') as f:
f.write(response.content)
```
注意:在实际使用中,需要根据具体情况设置请求头、代理等参数,以确保下载的文件正确无误。
python requests 下载图片
在Python中,你可以使用`requests`库来下载图片。下面是一个简单的示例代码:
```python
import requests
def download_image(url, save_path):
response = requests.get(url)
if response.status_code == 200:
with open(save_path, 'wb') as file:
file.write(response.content)
print("图片下载成功!")
else:
print("图片下载失败!")
# 调用函数下载图片
image_url = "https://example.com/image.jpg"
save_location = "path/to/save/image.jpg"
download_image(image_url, save_location)
```
在上面的代码中,`download_image`函数接受两个参数:图片的URL和保存路径。它使用`requests.get`方法发送GET请求获取图片的内容,并将内容写入到指定的文件中。
你只需要将`image_url`替换为你要下载的图片的URL,将`save_location`替换为你想要保存图片的路径和文件名即可。