在Python中,你可以使用 `wget` 库来下载文件。以下是使用 `wget` 库下载文件的步骤:
1. 安装 `wget` 库:
```bash
pip install wget
2. 导入 `wget` 库:
```python
import wget
3. 使用 `wget.download()` 方法下载文件:
```python
url = 'http://example.com/file.txt' 文件的URL
filename = wget.download(url) 下载文件,文件名与URL中的文件名一致
print(f'文件已下载到:{filename}') 打印下载的文件名
4. 若要下载文件并指定保存路径和文件名,可以使用 `out` 参数:
```python
url = 'http://example.com/file.txt' 文件的URL
save_path = '/path/to/your/directory/file.txt' 保存路径
filename = wget.download(url, out=save_path) 下载文件并指定保存路径
print(f'文件已保存到:{filename}') 打印保存的文件名
5. 若要下载整个网站,可以使用以下函数:
```python
import wget
import os
def download_site(url, save_path):
创建保存目录
os.makedirs(save_path, exist_ok=True)
设置下载选项
options = {
'recursive': True, 递归下载
'no_clobber': True, 不覆盖已存在的文件
'page_requisites': True, 下载页面依赖文件
'html_extension': True, 把html文件加上.html后缀
'convert_links': True, 转换链接为本地
'no_parent': True, 不下载父级目录
'directory_prefix': save_path 保存目录
}
开始下载
wget.download(url, options)
使用这些方法,你可以方便地从互联网上下载文件。