我有一个文件夹,其中包含一些目录和一些html文件。在这些目录中有一些HTML文件和一些文件夹,这将持续3/4的深度,直到最后。在
我正在尝试递归地遍历HTML,提取3个div,保存文件并转到下一个子文件夹,直到一切都完成。在
我认为我的代码很合理,但每当我尝试运行它时,标题中就会出现错误。我做错了什么?我只为一个文件夹运行代码,但我的递归不起作用。在
import os
from bs4 import BeautifulSoup
def CleanUpFolder(dir):
directory = os.listdir(dir)
files = []
for subdir, dirs, files in os.walk(dir):
for file in files:
if file.endswith('.html'):
files.insert(0, file)
for fileName in files:
file = open(dir + "\\" + fileName)
content = file.read()
file.close()
soup = BeautifulSoup(content)
toWrite = soup.find("div", {"class": "title"})
toWrite2 = soup.find("div", {"class": "main"})
toWrite3 = soup.find("div", {"class": "price"})
toCopy=""
if toWrite:
toCopy += str(toWrite)
if toWrite2:
toCopy += str(toWrite2)
if toWrite3:
toCopy += str(toWrite3)
file = open(dir + "\\" + fileName, 'w')
file.write(toCopy)
file.close()
for folder in dirs: #Recursive call here
if os.path.isdir(dir):
print dir
CleanUpFolder(dir)
dir = "C:\Users\FOLDER"
CleanUpFolder(dir)
我能做些什么来帮助我有效地解析这些数据?在
假设我的数据结构是6个目录,A、B、C、D、E和F。要导航到F,必须转到C:\Users\FOLDER\A\B\C\D\E\F
,每个目录中都有许多.html文件,而且可能还有多个文件夹。在
非常感谢您的时间和指导:)。在
问题是你的变量完全是一团糟。导致无限递归的代码是:
您调用的是
CleanUpFolder(dir)
,而不是CleanUpFolder(folder)
。在当您使用
os.walk
时,它在迭代器中执行递归操作,即最终它将遍历每个目录和子目录并列出每个文件。在这种情况下,您不需要为每个子目录递归调用CleanupFolder
。在我想你得到警告的原因是你打电话来手术室步行同时手术室步行已经在迭代,但我无法确认。在
相关问题 更多 >
编程相关推荐