用py的PySimpleGUI把以下程序做成可视化程序:选择网页,比如https://www.mingyannet.com/chengyu/1698055168.html网页文字和图片,并在界面选择保存到txt里面还是选择保存到word里
时间: 2023-12-31 15:03:22 浏览: 125
好的,以下是使用 PySimpleGUI 实现的代码:
``` python
import requests
from bs4 import BeautifulSoup
import PySimpleGUI as sg
from docx import Document
from docx.shared import Inches
def save_to_txt(url):
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
content = soup.find("div", {"class": "content"}).get_text()
with open("output.txt", "w", encoding="utf-8") as f:
f.write(content)
def save_to_word(url):
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
content = soup.find("div", {"class": "content"}).get_text()
document = Document()
document.add_heading("Content", 0)
document.add_paragraph(content)
document.add_picture("https://www.mingyannet.com/wp-content/themes/mytheme/images/logo.png", width=Inches(1.25))
document.save("output.docx")
sg.theme("Light Blue 2")
layout = [
[sg.Text("Please enter the URL of the webpage: ")],
[sg.InputText(key="-URL-")],
[sg.Radio("Save to txt file", "RADIO1", default=True, key="-TXT-"), sg.Radio("Save to word file", "RADIO1", key="-WORD-")],
[sg.Button("OK"), sg.Button("Cancel")]
]
window = sg.Window("Webpage Content Downloader", layout)
while True:
event, values = window.read()
if event == "OK":
url = values["-URL-"]
if values["-TXT-"]:
save_to_txt(url)
sg.popup("Content saved to output.txt")
elif values["-WORD-"]:
save_to_word(url)
sg.popup("Content saved to output.docx")
elif event == "Cancel" or event == sg.WIN_CLOSED:
break
window.close()
```
运行程序后,会弹出一个窗口,要求输入要下载的网页的 URL,并让用户选择将内容保存到 txt 文件还是 word 文件中。点击 OK 按钮后,程序会进行相应的操作,并在完成后弹出提示框。
注意:由于本人无法访问提供的网页,因此代码中的图片链接是随便找的一个图片链接,如需正确使用请替换为正确的链接。
阅读全文