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

2025-02-21 05:50

本文主要是介绍使用Python快速实现链接转word文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...

演示

使用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 colorjs: 字体颜色 (默认黑色)
    :return: 新创建的样式
    """
    style = document.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH)
    font = style.font
    font.name = font_name
    font.size = Pt(fonChina编程t_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 = phpRwww.chinasem.cnGBColor(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内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于使用Python快速实现链接转word文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153481

相关文章

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

python获取网页表格的多种方法汇总

《python获取网页表格的多种方法汇总》我们在网页上看到很多的表格,如果要获取里面的数据或者转化成其他格式,就需要将表格获取下来并进行整理,在Python中,获取网页表格的方法有多种,下面就跟随小编... 目录1. 使用Pandas的read_html2. 使用BeautifulSoup和pandas3.

PyQt6/PySide6中QTableView类的实现

《PyQt6/PySide6中QTableView类的实现》本文主要介绍了PyQt6/PySide6中QTableView类的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学... 目录1. 基本概念2. 创建 QTableView 实例3. QTableView 的常用属性和方法

Pandas透视表(Pivot Table)的具体使用

《Pandas透视表(PivotTable)的具体使用》透视表用于在数据分析和处理过程中进行数据重塑和汇总,本文就来介绍一下Pandas透视表(PivotTable)的具体使用,感兴趣的可以了解一下... 目录前言什么是透视表?使用步骤1. 引入必要的库2. 读取数据3. 创建透视表4. 查看透视表总结前言

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰

PyQt6/PySide6中QTreeView类的实现

《PyQt6/PySide6中QTreeView类的实现》QTreeView是PyQt6或PySide6库中用于显示分层数据的控件,本文主要介绍了PyQt6/PySide6中QTreeView类的实现... 目录1. 基本概念2. 创建 QTreeView 实例3. QTreeView 的常用属性和方法属性

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数

Golang HashMap实现原理解析

《GolangHashMap实现原理解析》HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持高效的插入、查找和删除操作,:本文主要介绍GolangH... 目录HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持