Python批量提取HTML页面Body内容的实战方案
本文介绍如何利用Python的BeautifulSoup库批量从城市美食及景点介绍等HTML页面中提取body标签内的具体内容。通过遍历目录结构并解析文件,实现自动化数据抓取与存储,为后续数据处理提供基础。
当前场景涉及一批完整的HTML页面,这些页面主要介绍城市美食和旅游景点等信息。目标是提取这些页面中body标签内的具体内容。
解决方案是采用Python插件BeautifulSoup来获取HTML中body标签的内容,并对这批文件进行批量处理。
# -*- coding:utf8 -*-
from bs4 import BeautifulSoup
import os
import os.path
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def printPath(level,path):
global allFileNum
#所有文件夹,第一个字段是此目录的级别
dirList = []
#所有文件
fileList = []
#返回一个列表,其中包含在目录条目的名称
files = os.listdir(path)
#先添加目录级别
dirList.append(str(level))
for f in files:
if(os.path.isdir(path+'/'+f)):
#排除隐藏文件夹,因为隐藏文件夹过多
if(f[0] == '.'):
pass
else:
#添加隐藏文件夹
dirList.append(f)
if(os.path.isfile(path+'/'+f)):
#添加文件
fileList.append(f)
return (dirList,fileList)
#将文件html文件抓取并写入指定txt文件
def getAndInsert(rootdir,savepath,path):
global file_num
f_list = os.listdir(rootdir+'/'+path)
for i in f_list:
temp = os.path.splitext(i)[0]
for num in range(1,11):
if(i==str(num)+'.html'):
#print rootdir+'/'+path+'/'+i
objFile = open(rootdir+'/'+path+'/'+i)
soup = BeautifulSoup(objFile)
arr = []
for child in soup.body:
arr.append(child)
if os.path.exists(savepath+'/'+path):
pass
else:
os.makedirs(savepath+'/'+path)
f = open(savepath+'/'+path+'/'+temp+'.txt','w')
for k,v in enumerate(arr):
if k!=1:
f.write(str(v))
f.close()
print path+'/'+i+' is running'
file_num = file_num + 1
rootdir = '../zips2'
dirList,fileList = printPath(1,rootdir)
savepath = "../testC"
file_num = 0
for fn in dirList:
if(fn == '1'):
pass
else:
getAndInsert(rootdir,savepath,fn)
print fn+' is ending'
print '一共完成'+str(file_num)+'个城市的提取'
以上关于Python批量获取HTML内body内容的实例分享完毕,希望能为大家提供参考。欢迎大家继续支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













