当前位置: 代码网 > it编程>前端脚本>Python > 使用Python快速实现链接转word文档

使用Python快速实现链接转word文档

2025年02月20日 Python 我要评论
演示代码展示from newspaper import articlefrom docx import documentfrom docx.shared import pt, rgbcolorfrom

演示

代码展示

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="网页链接", 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="转换", command=on_click, font=("arial", 16))
    button.pack(pady=20)

    # 运行主循环
    root.mainloop()

def fetch_article_content(url):
    """
    使用 newspaper3k 获取指定url页面的文章内容。
    
    :param url: 要抓取的网页url
    :return: 文章的元数据和正文内容
    """
    try:
        # 创建article对象
        article = article(url, language='zh')  # 设置语言为中文
        
        # 下载并解析文章
        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)):
    """
    创建一个自定义样式。
    
    :param document: 当前文档对象
    :param name: 样式名称
    :param font_size: 字体大小 (默认12)
    :param font_name: 字体名称 (默认arial)
    :param color: 字体颜色 (默认黑色)
    :return: 新创建的样式
    """
    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()

    # 创建一个自定义样式
    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)

    # 添加发布日期
    if article_info['publish_date']:
        document.add_paragraph(f"发布时间: {article_info['publish_date']}".encode('utf-8').decode('utf-8'), style=normal_style)

    # 添加正文
    document.add_heading('内容', 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('提示','转换成功')

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

到此这篇关于使用python快速实现链接转word文档的文章就介绍到这了,更多相关python链接转word内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com