使用Python快速實現(xiàn)鏈接轉(zhuǎn)word文檔
演示

代碼展示
from newspaper import Article
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn
# tkinter GUI
import tkinter as tk
from tkinter import messagebox
def init_window():
root = tk.Tk()
root.title("Url2Word-Tools")
root.geometry("400x300")
url_label = tk.Label(root, text="網(wǎng)頁鏈接", font=("Arial", 16))
url_label.pack(pady=20)
global url_input
url_input = tk.StringVar()
url_input = tk.Entry(root, textvariable=url_input, font=("Arial", 16))
url_input.pack(padx=20)
button = tk.Button(root, text="轉(zhuǎn)換", command=on_click, font=("Arial", 16))
button.pack(pady=20)
# 運行主循環(huán)
root.mainloop()
def fetch_article_content(url):
"""
使用 newspaper3k 獲取指定URL頁面的文章內(nèi)容。
:param url: 要抓取的網(wǎng)頁URL
:return: 文章的元數(shù)據(jù)和正文內(nèi)容
"""
try:
# 創(chuàng)建Article對象
article = Article(url, language='zh') # 設(shè)置語言為中文
# 下載并解析文章
article.download()
article.parse()
# 提取文章信息
article_info = {
'title': article.title,
'authors': article.authors,
'publish_date': article.publish_date,
'text': article.text,
'top_image': article.top_image,
'images': list(article.images),
'html': article.html
}
return article_info
except Exception as e:
print(f"Error fetching {url}: {e}")
return None
def create_style(document, name, font_size=12, font_name='Arial', color=RGBColor(0, 0, 0)):
"""
創(chuàng)建一個自定義樣式。
:param document: 當前文檔對象
:param name: 樣式名稱
:param font_size: 字體大小 (默認12)
:param font_name: 字體名稱 (默認Arial)
:param color: 字體顏色 (默認黑色)
:return: 新創(chuàng)建的樣式
"""
style = document.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH)
font = style.font
font.name = font_name
font.size = Pt(font_size)
font.color.rgb = color
return style
def set_run_style(run, font_size=12, font_name='Arial', color=RGBColor(0, 0, 0)):
run.font.name = font_name
run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
run.font.size = Pt(font_size)
run.font.color.rgb = color
def save_to_word(article_info, output_path):
"""
將文章信息保存為Word文檔。
:param article_info: 包含文章信息的字典
:param output_path: 輸出Word文檔的路徑
"""
document = Document()
# 創(chuàng)建一個自定義樣式
normal_style = create_style(document, 'CustomNormalStyle')
# 添加標題
heading = document.add_heading(article_info['title'], level=1)
for run in heading.runs:
# run.font.color.rgb = RGBColor(0, 0, 0) # 確保標題是黑色
set_run_style(run, font_size=20)
# 添加作者
if article_info['authors']:
authors_str = ', '.join(article_info['authors'].encode('utf-8').decode('utf-8'))
document.add_paragraph(f"作者: {authors_str}", style=normal_style)
# 添加發(fā)布日期
if article_info['publish_date']:
document.add_paragraph(f"發(fā)布時間: {article_info['publish_date']}".encode('utf-8').decode('utf-8'), style=normal_style)
# 添加正文
document.add_heading('內(nèi)容', level=2).runs[0].font.color.rgb = RGBColor(0, 0, 0)
paragraphs = article_info['text'].split('\n')
for paragraph in paragraphs:
if paragraph.strip(): # 忽略空行
clean_paragraph = paragraph.encode('utf-8').decode('utf-8')
p = document.add_paragraph(style=normal_style)
run = p.add_run(clean_paragraph)
set_run_style(run)
# 保存文檔
document.save(output_path)
print(f"Document saved to {output_path}")
messagebox.showinfo('提示','轉(zhuǎn)換成功')
def on_click():
url = url_input.get()
print(url)
article_info = fetch_article_content(f'{url}')
if article_info:
# print("Title:", article_info['title'])
# print("Authors:", article_info['authors'])
# print("Publish Date:", article_info['publish_date'])
# print("Text:\n", article_info['text'])
# print("Top Image:", article_info['top_image'])
# print("Images:", article_info['images'])
output_path = f"./{article_info['title']}.docx"
save_to_word(article_info, output_path)
if __name__ == "__main__":
init_window()最后
這里提供了打包好的 exe 供大家免費使用,GitHub 倉庫地址如下:python_tools
到此這篇關(guān)于使用Python快速實現(xiàn)鏈接轉(zhuǎn)word文檔的文章就介紹到這了,更多相關(guān)Python鏈接轉(zhuǎn)word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python調(diào)用MySql保姆級圖文教程(包會的)
MySQL是當今市場上最受歡迎的數(shù)據(jù)庫系統(tǒng)之一,由于大多數(shù)應(yīng)用程序需要以某種形式與數(shù)據(jù)交互,因此像Python這樣的編程語言提供了用于存儲和訪問這些數(shù)據(jù)的工具,這篇文章主要給大家介紹了關(guān)于python調(diào)用MySql的相關(guān)資料,需要的朋友可以參考下2024-12-12
python?pandas數(shù)據(jù)處理之刪除特定行與列
Pandas是數(shù)據(jù)科學(xué)中的利器,你可能想到的數(shù)據(jù)處理騷操作,貌似用Pandas都能夠?qū)崿F(xiàn),下面這篇文章主要給大家介紹了關(guān)于python?pandas數(shù)據(jù)處理之刪除特定行與列的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08
Python 棧實現(xiàn)的幾種方式及優(yōu)劣詳解
這篇文章主要為大家介紹了Python 棧實現(xiàn)的幾種方式及優(yōu)劣詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
Python實現(xiàn)音頻添加數(shù)字水印的示例詳解
數(shù)字水印技術(shù)可以將隱藏信息嵌入到音頻文件中而不明顯影響音頻質(zhì)量,下面小編將介紹幾種在Python中實現(xiàn)音頻數(shù)字水印的方法,希望對大家有所幫助2025-04-04
Java Web開發(fā)過程中登陸模塊的驗證碼的實現(xiàn)方式總結(jié)
Java的SSH三大Web開發(fā)框架中,對于驗證碼這一基本功能的處理都比較得心應(yīng)手,接下來我們就來看看整理出的Java Web開發(fā)過程中登陸模塊的驗證碼的實現(xiàn)方式總結(jié):2016-05-05
python使用兩種發(fā)郵件的方式smtp和outlook示例
本篇文章主要介紹了python使用兩種發(fā)郵件的方式smtp和outlook示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-06-06

