能用python写下载文件到本地的功能吗
时间: 2023-10-01 20:07:53 浏览: 41
当然可以,Python有内置的urllib和requests库可以用来下载文件。
以下是使用requests库下载文件的示例:
```python
import requests
url = 'http://example.com/file.txt'
response = requests.get(url)
# 检查响应状态码是否为200(表示成功)
if response.status_code == 200:
with open('file.txt', 'wb') as f:
f.write(response.content)
print('文件下载完成!')
else:
print('文件下载失败!')
```
这个代码片段将从`http://example.com`下载一个名为`file.txt`的文件,并将其保存在当前工作目录中。
如果你想使用urllib库,可以使用以下代码:
```python
import urllib.request
url = 'http://example.com/file.txt'
urllib.request.urlretrieve(url, 'file.txt')
print('文件下载完成!')
```
这个代码片段使用urllib库的`urlretrieve`方法来下载文件。它将从`http://example.com`下载一个名为`file.txt`的文件,并将其保存在当前工作目录中。
相关问题
用python写文件下载到本地的功能
以下是一个简单的Python程序,可以将文件从URL下载到本地:
```python
import urllib.request
url = "http://example.com/file.png"
local_file = "file.png"
urllib.request.urlretrieve(url, local_file)
```
这个程序使用Python标准库中的`urllib.request`模块来实现文件下载功能。`urlretrieve`函数将从指定的URL下载文件,并将文件保存到本地文件系统中的指定位置。
用python获取href中的pdf文件保存到本地
可以使用Python中的BeautifulSoup库和requests库来实现这个功能。首先,使用requests库获取网页的HTML代码,然后使用BeautifulSoup库解析HTML代码,找到所有的a标签,判断其中的href属性是否指向一个PDF文件,如果是,则使用requests库下载该PDF文件并保存到本地。
以下是示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://example.com' # 替换为你要获取PDF文件的网页链接
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
href = link.get('href')
if href.endswith('.pdf'):
pdf_response = requests.get(href)
with open(href.split('/')[-1], 'wb') as f:
f.write(pdf_response.content)
```
这段代码会在当前目录下保存所有找到的PDF文件。