不知不觉已经毕业一年多了,在这一年的时间里主要从事数据分析与挖掘方面工作,突然想把之前研究的技术做个总结整理进行分享。

        之前公司项目有个很奇葩的需求,希望能将网页数据爬取下来并保存到word中,要求与网页上一模一样,包括网页上图表内容。

这里以静态网页为例。首先展示下最终结果:

原网页部分截图内容:







通过爬虫写入word效果:







以上展示了单个网页数据写入word中的简单效果,其中图表相关信息爬取工作较为繁琐些。

单个网页数据爬取思路:首先解析网页,然后定位网页信息,接着判断所定位网页信息中的每段内容是否为表格或者图片。若为表格,则需要分析表格结构。

如下图所示可发现,tr表示表格的行,td表示表格的列。第一个tr下有4个td对应表中第一行4列,以此类推。图表的绘制主要用到python第三方包
python_docx,通过该包中add_table函数绘制表格,add_picture函数用于绘制图片。



 

Python使用python_docx包方法可参考网页:

http://www.cnblogs.com/ontheway703/p/5266041.html

该部分代码如下:
def get_article(url_body,filename,html): content_total = "" text =
url_body.xpath('.//td[@class="b12c"]/p|.//td[@class="b12c"]/div|.//td[@class="b12c"]/span|.//td[@class="b12c"]/font')
doc = Document() for x in text: row = x.xpath('.//tbody//tr') try: if row:
#判断是否为表格 for col in row: table = doc.add_table(rows=1, cols=int(len(col)),
style='Table Grid') hdr_cells = table.rows[0].cells td = col.xpath('./td')
td_list = [] for t in td: ins_data = t.xpath('.//text()') #爬取网页表格中的数据 ins_data
= filter(lambda x: x != '\r\n ', ins_data) tmp = "" for i in
range(len(ins_data)): tmp += ins_data[i] td_list.append(tmp) length =
len(td_list) for i in range(length): hdr_cells[i].text = td_list[i] #数据写入创建的表格中
else: img_ads = x.xpath('.//@src') imglist = "" if img_ads: #判断爬取的是否为图片数据 for h
in img_ads: if h.startswith('http://'): try: img =
cStringIO.StringIO(urllib2.urlopen(h).read()) except: img =
cStringIO.StringIO(req.get(h).content) else: #有些图片网页不是http:开头需要重新修改 ind =
html.rfind('/') + 1 h = html.replace(html[ind:], h) try: img =
cStringIO.StringIO(urllib2.urlopen(h).read()) except: img =
cStringIO.StringIO(req.get(h).content) doc.add_picture(img,
width=Inches(4.25))#设置写入的图片大小 imglist = imglist + h + " " paragraph =
x.xpath('.//text()') #爬取文字段落信息 str_ = "" for j in paragraph: str_ = str_ + j
doc.add_paragraph(str_) content_total = content_total + imglist + str_ + "\n"
except: pass doc.save(filename) return content_total

本文简单介绍单个网页数据的爬取写入方法,爬取的目标网页为静态网页。若为动态网页还需要查找出网页的跳转文件。对多个网页爬取则需要进行分页处理,可使用MongoDB将爬取的网页地址存入MongoDB中,每次爬取网页可进行判断MongoDB中是否存在以免重复爬取。

本文实例源码:


https://github.com/liangjunAI/Spider/blob/master/spider_into_word/spider_in_word.py

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信