python批量获取html内body内容的实例

yipeiwu_com5年前Python基础

现在有一批完整的关于介绍城市美食、景点等的html页面,需要将里面body的内容提取出来

方法:利用python插件beautifulSoup获取htmlbody标签的内容,并批量处理。

# -*- 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内容的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python主线程与子线程的结束顺序实例解析

这篇文章主要介绍了python主线程与子线程的结束顺序实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 引用自 主线程退出对子线...

Tensorflow 查看变量的值方法

定义一个变量,直接输出会输出变量的属性,并不能输出变量值。那么怎么输出变量值呢?请看下面得意 import tensorflow as tf biases=tf.Variable(...

Python输入二维数组方法

前不久对于Python输入二维数组有些不解,今日成功尝试,记以备忘。这里以输入1-9,3*3矩阵为例 n=int(input()) line=[[0]*n]*n for i in r...

python二维列表一维列表的互相转换实例

二维列表转一维列表 from compiler.ast import flatten a=[[1,2],[5,6]] print(flatten(a)) 结果:[1, 2, 5,...

Python探索之ModelForm代码详解

这是一个神奇的组件,通过名字我们可以看出来,这个组件的功能就是把model和form组合起来,对,你没猜错,相信自己的英语水平。 先来一个简单的例子来看一下这个东西怎么用: 比如我们...