爬虫抓取网页数据(单个网页数据爬取的思路及技术做个)
优采云 发布时间: 2021-11-14 19:02爬虫抓取网页数据(单个网页数据爬取的思路及技术做个)
不知不觉,我已经毕业一年多了。这一年主要从事数据分析和挖掘。突然想总结分享一下之前学过的技术。
之前公司项目有一个很奇怪的需求,希望抓取网页数据并保存在Word中,要求和网页上一模一样,包括网页上图表的内容。
以静态网页为例。先展示最终结果:
部分原网页截图:
通过爬虫写字效果:
上面是将单个网页的数据写入word的简单效果,爬取图表相关信息的工作比较繁琐。
爬取单个网页数据的思路:先解析网页,然后定位网页信息,再判断定位到的网页信息中的每条内容是表格还是图片。如果是表,则需要分析表结构。
如下图,tr代表表格的行,td代表表格的列。第一个tr下有4个td对应表的第一行4列,以此类推。图表的绘制主要使用python第三方包python_docx,通过该包中的add_table函数绘制表格,使用add_picture函数绘制图片。
Python使用python_docx包方法来引用网页:
这部分代码如下:
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中是否有,避免重复爬取。
本文示例的源代码: