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

 更新时间:2025年02月20日 15:39:39   作者:嘿嘿潶黑黑  
这篇文章主要为大家详细介绍了如何使用Python快速实现链接转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="网页链接", 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python调用MySql保姆级图文教程(包会的)

    python调用MySql保姆级图文教程(包会的)

    MySQL是当今市场上最受欢迎的数据库系统之一,由于大多数应用程序需要以某种形式与数据交互,因此像Python这样的编程语言提供了用于存储和访问这些数据的工具,这篇文章主要给大家介绍了关于python调用MySql的相关资料,需要的朋友可以参考下
    2024-12-12
  • python pandas数据处理之删除特定行与列

    python pandas数据处理之删除特定行与列

    Pandas是数据科学中的利器,你可能想到的数据处理骚操作,貌似用Pandas都能够实现,下面这篇文章主要给大家介绍了关于python pandas数据处理之删除特定行与列的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • Python 栈实现的几种方式及优劣详解

    Python 栈实现的几种方式及优劣详解

    这篇文章主要为大家介绍了Python 栈实现的几种方式及优劣详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • Python制作动态字符图的实例

    Python制作动态字符图的实例

    今天小编就为大家分享一篇关于Python制作动态字符图的实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Python实现音频添加数字水印的示例详解

    Python实现音频添加数字水印的示例详解

    数字水印技术可以将隐藏信息嵌入到音频文件中而不明显影响音频质量,下面小编将介绍几种在Python中实现音频数字水印的方法,希望对大家有所帮助
    2025-04-04
  • Django零基础入门之常用过滤器详解

    Django零基础入门之常用过滤器详解

    这篇文章主要介绍了Django零基础入门之常用过滤器的使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09
  • Java Web开发过程中登陆模块的验证码的实现方式总结

    Java Web开发过程中登陆模块的验证码的实现方式总结

    Java的SSH三大Web开发框架中,对于验证码这一基本功能的处理都比较得心应手,接下来我们就来看看整理出的Java Web开发过程中登陆模块的验证码的实现方式总结:
    2016-05-05
  • python绘制简单折线图代码示例

    python绘制简单折线图代码示例

    这篇文章主要介绍了python绘制简单折线图代码示例,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • python使用两种发邮件的方式smtp和outlook示例

    python使用两种发邮件的方式smtp和outlook示例

    本篇文章主要介绍了python使用两种发邮件的方式smtp和outlook示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-06-06
  • 深入了解python高阶函数编写与使用

    深入了解python高阶函数编写与使用

    这篇文章主要为大家介绍了python高阶函数编写与使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助<BR>
    2021-11-11

最新评论