Python解析HTML提取数据并生成Word文档的完整实现

沈亦白
沈亦白
发布时间:2026-10-13| 3人浏览过
原创

本文详细介绍如何利用Python解析HTML网页内容并生成Word文档。通过安装setuptools和python-docx组件,结合sgmllib与urllib获取数据,实现了从网页抓取到文档生成的自动化流程。文中提供了完整的代码示例及安装步骤,适用于需要批量处理网页数据并导出为Word格式的场景。

简介

本文记录了一个使用Python抓取网页内容并生成Word文档的简单功能实现,旨在为后续类似需求提供参考。

生成Word文档使用了第三方库python-docx,因此首先需要完成该组件的安装。需要注意的是,Windows环境下默认安装的Python可能未包含setuptools模块,因此需先安装setuptools。

安装步骤

1. 访问Python官网提供的链接 https://bootstrap.pypa.io/ez_setup.py ,将代码保存至本地并执行命令:python ez_setup.py。

2. 下载python-docx(地址:https://pypi.python.org/pypi/python-docx/0.7.4),解压后进入目录 XXX\python-docx-0.7.4 ,执行命令 python setup.py install 进行安装。

安装完成后,即可使用python-docx操作Word文档。关于Word文档生成的具体用法,可参考官方文档:https://python-docx.readthedocs.org/en/latest/index.html。

HTML解析部分使用了sgmllib模块中的SGMLParser类,URL内容的获取则依赖于urllib和urllib2模块。

实现代码

# -*- coding: cp936 -*- 
from sgmllib import SGMLParser 
import os 
import sys 
import urllib 
import urllib2 
from docx import Document 
from docx.shared import Inches 
import time 
 
##获取要解析的url 
class GetUrl(SGMLParser): 
  def __init__(self): 
    SGMLParser.__init__(self) 
    self.start=False 
    self.urlArr=[] 
 
 
  def start_div(self,attr): 
    for name,value in attr: 
      if value=="ChairmanCont Bureau":#页面js中的固定值 
        self.start=True 
 
 
  def end_div(self): 
    self.start=False 
 
 
  def start_a(self,attr): 
    if self.start: 
      for name,value in attr: 
        self.urlArr.append(value) 
       
 
 
  def getUrlArr(self): 
    return self.urlArr 
   
##解析上面获取的url,获取有用数据 
class getManInfo(SGMLParser): 
  def __init__(self): 
    SGMLParser.__init__(self) 
    self.start=False 
    self.p=False 
    self.dl=False 
    self.manInfo=[] 
    self.subInfo=[] 
 
  def start_div(self,attr): 
    for name,value in attr: 
      if value=="SpeakerInfo":#页面js中的固定值 
        self.start=True 
 
  def end_div(self): 
    self.start=False 
 
  def start_p(self,attr): 
    if self.dl: 
      self.p=True 
 
  def end_p(self): 
    self.p=False 
 
  def start_img(self,attr): 
    if self.dl: 
      for name,value in attr: 
        self.subInfo.append(value) 
     
 
 
  def handle_data(self,data): 
    if self.p: 
      self.subInfo.append(data.decode('utf-8')) 
 
 
  def start_dl(self,attr): 
    if self.start: 
      self.dl=True 
 
  def end_dl(self): 
    self.manInfo.append(self.subInfo) 
    self.subInfo=[] 
    self.dl=False 
 
  def getManInfo(self): 
    return self.manInfo 
 
 
 
         
 
urlSource="http://www.XXX" 
sourceData=urllib2.urlopen(urlSource).read() 
 
startTime=time.clock() 
##get urls 
getUrl=GetUrl() 
getUrl.feed(sourceData) 
urlArr=getUrl.getUrlArr() 
getUrl.close() 
print "get url use:" + str((time.clock() - startTime)) 
startTime=time.clock() 
 
 
##get maninfos 
manInfos=getManInfo() 
for url in urlArr:#one url one person 
  data=urllib2.urlopen(url).read() 
  manInfos.feed(data) 
infos=manInfos.getManInfo() 
manInfos.close() 
print "get maninfos use:" + str((time.clock() - startTime)) 
startTime=time.clock() 
 
#word 
saveFile=os.getcwd()+"\\xxx.docx" 
doc=Document() 
##word title 
doc.add_heading("HEAD".decode('gbk'),0) 
p=doc.add_paragraph("HEADCONTENT:".decode('gbk')) 
 
 
##write info 
for infoArr in infos: 
  i=0 
  for info in infoArr: 
    if i==0:##img url 
      arr1=info.split('.') 
      suffix=arr1[len(arr1)-1] 
      arr2=info.split('/') 
      preffix=arr2[len(arr2)-2] 
      imgFile=os.getcwd()+"\\imgs\\"+preffix+"."+suffix 
      if not os.path.exists(os.getcwd()+"\\imgs"): 
        os.mkdir(os.getcwd()+"\\imgs") 
      imgData=urllib2.urlopen(info).read() 
 
      try: 
        f=open(imgFile,'wb') 
        f.write(imgData) 
        f.close() 
        doc.add_picture(imgFile,width=Inches(1.25)) 
        os.remove(imgFile) 
      except Exception as err: 
        print (err) 
  
       
    elif i==1: 
      doc.add_heading(info+":",level=1) 
    else: 
      doc.add_paragraph(info,style='ListBullet') 
    i=i+1 
 
   
doc.save(saveFile) 
print "word use:" + str((time.clock() - startTime)) 

总结

以上即为Python解析HTML提取数据并生成Word文档的完整实例解析,希望能对大家有所帮助。感兴趣的朋友可以继续查阅本站其他相关专题,如有不足之处,欢迎留言指正。感谢各位的支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。