python批量獲取html內body內容的實例
更新時間:2019年01月02日 08:42:01 作者:STKi
今天小編就為大家分享一篇python批量獲取html內body內容的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
現(xiàn)在有一批完整的關于介紹城市美食、景點等的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內容的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Selenium執(zhí)行完畢未關閉chromedriver/geckodriver進程的解決辦法(java版+python版
這篇文章主要介紹了Selenium執(zhí)行完畢未關閉chromedriver/geckodriver進程的解決辦法(java版+python版),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
淺談Django學習migrate和makemigrations的差別
這篇文章主要介紹了淺談Django學習migrate和makemigrations的差別,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
一文帶你了解Python中不同數(shù)據對象的空值校驗方法
空值校驗在數(shù)據處理和應用程序開發(fā)中是一個非常重要的任務,Python提供了多種方式來檢查不同數(shù)據對象(如字符串、列表、字典、集合等)是否為空或包含空值,下面就跟隨小編一起來學習一下吧2024-01-01

