如何使用Python爬取网页并保存为Word文档

您所在的位置:网站首页 网页内容怎么做成文档 如何使用Python爬取网页并保存为Word文档

如何使用Python爬取网页并保存为Word文档

2024-07-16 01:07| 来源: 网络整理| 查看: 265

假设您是一位热衷于收集好文章的人,每天都希望能够快速获取优质文章并保存在本地,以备离线阅读。但是,手动复制粘贴文章内容并保存为Word文档是一项繁琐的任务,特别是当您需要获取大量文章时。在这篇教程中,我将向您介绍如何使用Python编写一个简单但功能强大的网络爬虫,可以帮助您自动从网站上获取文章并保存为Word文档,让您更轻松地构建自己的文章库。

准备工作

在开始之前,我们需要准备一些工具和环境:

Python环境:确保您已经安装了Python,最好使用Python 3.x版本。您可以在Python官网上下载并安装最新版本的Python。

代码编辑器:选择一个您喜欢的代码编辑器,例如PyCharm或Visual Studio Code,以便编写Python脚本。

必要的库:在本教程中,我们将使用Requests、Beautiful Soup和docx库来进行网络请求、解析HTML和创建Word文档。您可以使用以下命令来安装这些库:

pip install requests beautifulsoup4 python-docx

网络连接:确保您的计算机能够连接到互联网,因为我们将从网页上获取文章内容。

编写Python爬虫脚本

以下是我们的Python爬虫脚本,它将从指定网站上获取文章并保存为Word文档:

# -*- coding: utf-8 -*- import time import random import requests import re from bs4 import BeautifulSoup from w3lib.html import remove_tags from docx.oxml.ns import qn from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import Pt from docx.shared import RGBColor # 爬取网页 def get_url(URL, SIGN): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'} html = requests.get(URL, headers=headers) html.encoding = 'utf-8' soup = BeautifulSoup(html.text, 'lxml') text = soup.select(SIGN) return text # 创建doc def get_docx(TITLE, BODY): document = Document() head0 = document.add_heading(level=1) head0.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER title_run = head0.add_run(TITLE) title_run.font.size = Pt(24) title_run.font.name = 'Times New Roman' title_run.element.rPr.rFonts.set(qn('w:eastAsia'), '方正小标宋简体') title_run.font.color.rgb = RGBColor(0, 0, 0) document.styles['Normal'].font.name = '宋体' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312') p = document.add_paragraph() p_run = p.add_run(BODY) p.paragraph_format.space_before = Pt(30) p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY p.paragraph_format.line_spacing = Pt(28.8) p.paragraph_format.first_line_indent = Inches(0.5) p_run.font.color.rgb = RGBColor(0, 0, 0) p_run.font.size = Pt(16) TITLE = re.sub('([^\u4e00-\u9fa5\d])', '', TITLE) name = 'D:\\Download\\Articles\\' + TITLE + '.docx' document.save(name) def main(): n = 0 menus = get_url('http://www.haoword.com', '.infobox .indexleft .infoco .lm .news_title h2 a') menus_url = [] for menu_url in menus: menus_url.append(menu_url['href']) print(menus_url) for menu_url in menus_url: time.sleep(random.random()) results = get_url(menu_url, '.infobox .lmleft .infoco2 .lm_addon .articles3 ul li a') for result in results: title_url = result['href'] title = result['title'] print(f'{title}:{title_url}') time.sleep(random.random()) articles_results = get_url(title_url, '.infobox .detail .content p')[1:] body = remove_tags(str(articles_results))[1:] get_docx(title, body) n += 1 print(f'爬取完毕!共爬取 {n} 篇文章。') if __name__ == '__main__': start = time.perf_counter() main() end = time.perf_counter() print(f'耗时 {end - start} 秒。') 使用说明

在脚本中,我们使用了Requests库来发送HTTP请求,Beautiful Soup来解析HTML内容,以及docx库来创建Word文档。

通过修改get_url函数中的URL和SIGN参数,您可以指定要爬取的网站和文章内容的选择器。

修改get_docx函数中的文档保存路径和格式以适应您的需求。

运行脚本后,它将自动从指定网站上获取文章并保存为Word文档。

总结

通过这篇教程,您学会了如何使用Python编写一个简单的网络爬虫,用于爬取网站上的文章并保存为Word文档。这个脚本可以帮助您轻松地建立自己的文章库,方便离线阅读和收藏。希望这对您有所帮助!

本文由作者 王大神 原创发布于 大神网的AI博客。

转载请注明作者:王大神

原文出处:如何使用Python爬取网页并保存为Word文档



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3