使用Python快速實(shí)現(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)頁(yè)鏈接", 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)
# 運(yùn)行主循環(huán)
root.mainloop()
def fetch_article_content(url):
"""
使用 newspaper3k 獲取指定URL頁(yè)面的文章內(nèi)容。
:param url: 要抓取的網(wǎng)頁(yè)URL
:return: 文章的元數(shù)據(jù)和正文內(nèi)容
"""
try:
# 創(chuàng)建Article對(duì)象
article = Article(url, language='zh') # 設(shè)置語(yǔ)言為中文
# 下載并解析文章
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)建一個(gè)自定義樣式。
:param document: 當(dāng)前文檔對(duì)象
:param name: 樣式名稱
:param font_size: 字體大小 (默認(rèn)12)
:param font_name: 字體名稱 (默認(rèn)Arial)
:param color: 字體顏色 (默認(rèn)黑色)
: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)建一個(gè)自定義樣式
normal_style = create_style(document, 'CustomNormalStyle')
# 添加標(biāo)題
heading = document.add_heading(article_info['title'], level=1)
for run in heading.runs:
# run.font.color.rgb = RGBColor(0, 0, 0) # 確保標(biāo)題是黑色
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ā)布時(shí)間: {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 供大家免費(fèi)使用,GitHub 倉(cāng)庫(kù)地址如下:python_tools
到此這篇關(guān)于使用Python快速實(shí)現(xiàn)鏈接轉(zhuǎn)word文檔的文章就介紹到這了,更多相關(guān)Python鏈接轉(zhuǎn)word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python實(shí)現(xiàn)pdf轉(zhuǎn)word詳細(xì)代碼
- Python實(shí)現(xiàn)PDF轉(zhuǎn)Word的多種方式總結(jié)
- Python實(shí)現(xiàn)HTML轉(zhuǎn)Word的示例代碼
- Python將Office文檔(Word、Excel、PDF、PPT)轉(zhuǎn)為OFD格式的實(shí)現(xiàn)方法
- 使用Python轉(zhuǎn)換Markdown文件為Word文檔
- Python中PDF轉(zhuǎn)Word的多種實(shí)現(xiàn)方法
- 基于Python實(shí)現(xiàn)Word文檔與SVG格式的相互轉(zhuǎn)換
相關(guān)文章
Python?subprocess.Popen?實(shí)時(shí)輸出?stdout的解決方法(正確管道寫法)
這篇文章主要介紹了Python?subprocess.Popen實(shí)時(shí)輸出stdout正確管道寫法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
Python 字符串裁切與提取全面且實(shí)用的解決方案
本文梳理了Python字符串處理方法,涵蓋基礎(chǔ)切片、split/partition分割、正則匹配及結(jié)構(gòu)化數(shù)據(jù)解析(如BeautifulSoup、json庫(kù)),并提供場(chǎng)景選擇建議與注意事項(xiàng),感興趣的朋友跟隨小編一起看看吧2025-08-08
conda管理Python虛擬環(huán)境的實(shí)現(xiàn)
本文主要介紹了conda管理Python虛擬環(huán)境的實(shí)現(xiàn),主要包括使用conda工具創(chuàng)建、查看和刪除Python虛擬環(huán)境,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
python 實(shí)現(xiàn)將多條曲線畫在一幅圖上的方法
今天小編就為大家分享一篇python 實(shí)現(xiàn)將多條曲線畫在一幅圖上的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Python內(nèi)置類型性能分析過(guò)程實(shí)例
這篇文章主要介紹了Python內(nèi)置類型性能分析過(guò)程實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
Django1.9 加載通過(guò)ImageField上傳的圖片方法
今天小編就為大家分享一篇Django1.9 加載通過(guò)ImageField上傳的圖片方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05

