python解析html提取数据,并生成word文档实例解析


Posted in Python onJanuary 22, 2018

简介

今天试着用ptyhon做了一个抓取网页内容,并生成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-docx : 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 相关文章推荐
Python实现批量更换指定目录下文件扩展名的方法
Sep 19 Python
Python实现购物车购物小程序
Apr 18 Python
Python判断两个list是否是父子集关系的实例
May 04 Python
十分钟利用Python制作属于你自己的个性logo
May 07 Python
Python静态类型检查新工具之pyright 使用指南
Apr 26 Python
Python/Django后端使用PIL Image生成头像缩略图
Apr 30 Python
使用Python实现毫秒级抢单功能
Jun 06 Python
详解pandas使用drop_duplicates去除DataFrame重复项参数
Aug 01 Python
python爬虫增加访问量的方法
Aug 22 Python
适合Python初学者的一些编程技巧
Feb 12 Python
记一次python 爬虫爬取深圳租房信息的过程及遇到的问题
Nov 24 Python
python 操作excel表格的方法
Dec 05 Python
Python复制Word内容并使用格式设字体与大小实例代码
Jan 22 #Python
Python读取word文本操作详解
Jan 22 #Python
python导出hive数据表的schema实例代码
Jan 22 #Python
Python的SimpleHTTPServer模块用处及使用方法简介
Jan 22 #Python
一道python走迷宫算法题
Jan 22 #Python
浅谈使用Python内置函数getattr实现分发模式
Jan 22 #Python
python正则表达式及使用正则表达式的例子
Jan 22 #Python
You might like
如何使用PHP中的字符串函数
2006/10/09 PHP
PHP教程 预定义变量
2009/10/23 PHP
在PHP中操作Excel实例代码
2010/04/29 PHP
新浪SAE云平台下使用codeigniter的数据库配置
2014/06/12 PHP
php使用curl获取https请求的方法
2015/02/11 PHP
PHP读MYSQL中文乱码的快速解决方法
2016/10/01 PHP
PHP载入图像imagecreatefrom_gif_jpeg_png系列函数用法分析
2016/11/14 PHP
使用WAMP搭建PHP本地开发环境
2017/05/10 PHP
javascript 异常处理使用总结
2009/06/21 Javascript
JavaScript获取短信验证码(周期性)
2016/12/29 Javascript
jQuery插件MovingBoxes实现左右滑动中间放大图片效果
2017/02/28 Javascript
jQuery选取所有复选框被选中的值并用Ajax异步提交数据的实例
2017/08/04 jQuery
Django与Vue语法的冲突问题完美解决方法
2017/12/14 Javascript
jQuery实现的记住帐号密码功能完整示例
2019/08/03 jQuery
layui 图片上传+表单提交+ Spring MVC的实例
2019/09/21 Javascript
在vue中实现清除echarts上次保留的数据(亲测有效)
2020/09/09 Javascript
python3编写C/S网络程序实例教程
2014/08/25 Python
python图像处理之镜像实现方法
2015/05/30 Python
Python中装饰器高级用法详解
2017/12/25 Python
磁盘垃圾文件清理器python代码实现
2020/08/24 Python
python 通过logging写入日志到文件和控制台的实例
2018/04/28 Python
Pandas 同元素多列去重的实例
2018/07/03 Python
python中wx模块的具体使用方法
2020/05/15 Python
Python timeit模块原理及使用方法
2020/10/10 Python
分享全球十款超强HTML5开发工具
2014/05/14 HTML / CSS
Feelunique澳大利亚:欧洲的化妆品零售电商
2019/12/18 全球购物
Linden Leaves官网:新西兰纯净护肤品
2020/12/20 全球购物
高级方案规划工程师岗位职责
2013/11/29 职场文书
历史专业个人求职信范文
2013/12/07 职场文书
教师的实习鉴定
2013/12/15 职场文书
中西医专业毕业生职业规划书
2014/02/24 职场文书
验房委托书
2014/08/30 职场文书
店面出租协议书范本
2014/11/28 职场文书
合作合同协议书范本
2015/01/27 职场文书
高中军训感想
2015/08/07 职场文书
Golang实现AES对称加密的过程详解
2021/05/20 Golang