用Python写一段代码,是一个TK界面,可以输入百度文库的url,点击下载按钮,即可将输入url的文档下载在 D:\小杜\杜悦菲 中
时间: 2024-02-12 22:09:49 浏览: 25
好的,我可以为您编写这段代码。不过在代码实现之前,需要安装两个 Python 库:requests 和 bs4。您可以使用以下命令进行安装:
```
pip install requests
pip install beautifulsoup4
```
安装完成后,以下是代码实现:
```python
import os
import requests
import tkinter as tk
from bs4 import BeautifulSoup
def download_doc():
url = entry_url.get()
if not url:
return
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
title = soup.find('title').text.replace('\n', '').replace('\r', '').replace(' ', '')
doc_url = soup.find('iframe')['src']
doc_res = requests.get(doc_url, headers=headers)
with open(os.path.join("D:/小杜/杜悦菲", f"{title}.docx"), "wb") as f:
f.write(doc_res.content)
window = tk.Tk()
window.title("下载文档")
window.geometry("400x100")
label_url = tk.Label(window, text="请输入百度文库的URL:")
label_url.pack()
entry_url = tk.Entry(window)
entry_url.pack()
btn_download = tk.Button(window, text="下载", command=download_doc)
btn_download.pack()
window.mainloop()
```
代码说明:
1. 通过 requests 库进行网页请求,获取网页内容;
2. 通过 bs4 库解析网页内容,获取文档的标题和下载链接;
3. 通过 requests 库下载文档,并保存在指定文件夹中。
请将代码保存为 download_doc.py 文件,使用 Python 运行即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)