【发布时间】:2020-04-05 05:53:43
【问题描述】:
当我尝试使用“xml”作为prettify() 格式的键时,出现错误。
这是我的代码,我试图将其解析为“xml”。但是当我尝试使用“html”作为键时,它可以正常工作。事实上,以 'minimal' 作为键,它工作得很好。
from bs4 import BeautifulSoup
doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soupy = BeautifulSoup(doc, 'html.parser')
soupy.body.b.prettify(formatter='xml')
输出:我已经通过 element.py 并因此到达 Formatter.py(class Formatter) 但仍然无法解决它!
KeyError Traceback(most recent call last)
<ipython-input-22-27d5e242bc68 > in < module >
--- -> 1 soupy.body.b.prettify(formatter='xml')
~/anaconda3/lib/python3.7/site-packages/bs4/element.py in prettify(self, encoding, formatter)
1575 """
1576 if encoding is None:
-> 1577 return self.decode(True, formatter=formatter)
1578 else:
1579 return self.encode(encoding, True, formatter=formatter)
~/anaconda3/lib/python3.7/site-packages/bs4/element.py in decode(self, indent_level, eventual_encoding, formatter)
1472 # over again.
1473 if not isinstance(formatter, Formatter):
-> 1474 formatter = self.formatter_for_name(formatter)
1475 attributes = formatter.attributes(self)
1476 attrs = []
~/anaconda3/lib/python3.7/site-packages/bs4/element.py in formatter_for_name(self, formatter)
195 if isinstance(formatter, Callable):
196 return c(entity_substitution=formatter)
--> 197 return c.REGISTRY[formatter]
198
199 @property
KeyError: 'xml'
提前谢谢,我只是想知道为什么会这样?
【问题讨论】:
标签: html xml web-scraping beautifulsoup