python批量獲取html內(nèi)body內(nèi)容的實(shí)例-創(chuàng)新互聯(lián)

現(xiàn)在有一批完整的關(guān)于介紹城市美食、景點(diǎn)等的html頁(yè)面,需要將里面body的內(nèi)容提取出來(lái)

創(chuàng)新互聯(lián)建站長(zhǎng)期為近千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為吉木乃企業(yè)提供專業(yè)的做網(wǎng)站、網(wǎng)站建設(shè),吉木乃網(wǎng)站改版等技術(shù)服務(wù)。擁有十年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。

方法:利用python插件beautifulSoup獲取htmlbody標(biāo)簽的內(nèi)容,并批量處理。

# -*- coding:utf8 -*-
 
from bs4 import BeautifulSoup
import os
import os.path
import sys
reload(sys) 
sys.setdefaultencoding('utf8') 
 
 
def printPath(level,path):
	global allFileNum
	#所有文件夾,第一個(gè)字段是此目錄的級(jí)別
	dirList = []
 
	#所有文件
	fileList = []
 
	#返回一個(gè)列表,其中包含在目錄條目的名稱
	files = os.listdir(path)
 
	#先添加目錄級(jí)別
	dirList.append(str(level))
 
	for f in files:
		if(os.path.isdir(path+'/'+f)):
			#排除隱藏文件夾,因?yàn)殡[藏文件夾過(guò)多
			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)+'個(gè)城市的提取'

本文標(biāo)題:python批量獲取html內(nèi)body內(nèi)容的實(shí)例-創(chuàng)新互聯(lián)
分享路徑:http://www.muchs.cn/article22/cshhjc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、靜態(tài)網(wǎng)站App開(kāi)發(fā)、企業(yè)建站微信小程序、品牌網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都app開(kāi)發(fā)公司