【发布时间】:2018-04-20 16:49:04
【问题描述】:
我是 Python 新手,BeautifulSoup 请耐心等待...
我正在尝试弄清楚如何使用 Beautifulsoup4 从 HTML 文件中删除 Doctype,但似乎无法确切地弄清楚如何实现这一点。
def saveToText(self):
filename = os.path.join(self.parent.ReportPath, str(self.parent.CharName.text()) + "_report.txt")
filename, filters = QFileDialog.getSaveFileName(self, "Save Report", filename, "Text (*.txt);;All Files (*.*)")
if filename is not None and str(filename) != '':
try:
if re.compile('\.txt$').search(str(filename)) is None:
filename = str(filename)
filename += '.txt'
soup = BeautifulSoup(self.reportHtml, "lxml")
try: # THROWS AttributeError IF NOT FOUND ..
soup.find('font').extract()
except AttributeError:
pass
try: # THROWS AttributeError IF NOT FOUND ..
soup.find('head').extract()
except AttributeError:
pass
soup.html.unwrap()
soup.body.unwrap()
for b in soup.find_all('b'):
b.unwrap()
for table in soup.find_all('table'):
table.unwrap()
for td in soup.find_all('td'):
td.unwrap()
for br in soup.find_all('br'):
br.replace_with('\n')
for center in soup.find_all('center'):
center.insert_after('\n')
for dl in soup.find_all('dl'):
dl.insert_after('\n')
for dt in soup.find_all('dt'):
dt.insert_after('\n')
for hr in soup.find_all('hr'):
hr.replace_with(('-' * 80) + '\n')
for tr in soup.find_all('tr'):
tr.insert_before(' ')
tr.insert_after('\n')
print(soup)
except IOError:
QMessageBox.critical(None, 'Error!', 'Error writing to file: ' + filename, 'OK')
我尝试使用:
from bs4 import Doctype
if isinstance(e, Doctype):
e.extract()
但这抱怨'e'是一个未解决的参考。我已经搜索了文档和谷歌,但我没有找到任何有用的东西。
顺便说一句,有没有办法减少这段代码?
【问题讨论】:
-
你在哪里定义了
e? -
@SamChats 我没有,我确定这就是为什么会发生这种情况,但我正在处理的示例也没有。我不确定'e'应该被定义为什么。 Beautifulsoup 的文档相当不错,但确实没有足够的信息让我离开。
-
也许
e只是对主要soup的引用? -
@SamChats 尝试在里面放汤;错误消失了,但 Doctype 仍然在我的输出中。
-
那么错误在于您尝试删除它的方式,在代码的上部。对了,你为什么要替换
trs?
标签: python python-3.x beautifulsoup