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

作者:yukiMark 时间:2023-10-19 13:50:38 

简介

今天试着用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里的SGMLParserurl内容的获取用到的是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))

总结

来源:http://blog.csdn.net/how8586/article/details/39399217

标签:python,爬虫,html,word
0
投稿

猜你喜欢

  • Python利用cv2动态绘制圆和矩形的示例详解

    2022-08-20 08:23:15
  • 详细讲解Access数据库远程连接的实用方法

    2008-11-28 16:34:00
  • django实现前后台交互实例

    2022-04-12 20:53:33
  • Python3使用TCP编写一个简易的文件下载器功能

    2021-02-20 09:58:07
  • js实现向右横向滑出的二级菜单效果

    2024-04-17 10:34:44
  • mysql 5.7.23 winx64解压版安装教程

    2024-01-26 01:41:09
  • python 实现数字字符串左侧补零的方法

    2021-07-07 10:34:43
  • mssql2005,2008导出数据字典实现方法

    2023-07-23 19:11:30
  • python opencv画局部放大图实例教程

    2023-12-01 09:55:55
  • vue相关配置文件详解及多环境配置详细步骤

    2023-07-02 16:39:39
  • Update 语句

    2009-06-22 12:52:00
  • Python 字符串操作实现代码(截取/替换/查找/分割)

    2023-07-14 06:14:00
  • [翻译]标记语言和样式手册 Chapter 9 精简标签

    2008-02-01 09:55:00
  • 微信小程序创建自定义全局函数以及其调用方法详解

    2023-08-24 20:43:22
  • Access 2002的三个实用技巧

    2007-10-22 12:22:00
  • 不知道这5种下划线的含义,你就不算真的会Python!

    2021-02-03 14:38:26
  • Python 异之如何同时运行多个协程详解

    2023-11-27 12:47:23
  • Python使用matplotlib绘制多个图形单独显示的方法示例

    2022-02-13 09:45:44
  • Jupyter notebook 远程配置及SSL加密教程

    2021-06-24 07:15:06
  • Dreamweaver基础技巧全面接触

    2010-03-25 12:23:00
  • asp之家 网络编程 m.aspxhome.com