Python BeautifulSoup HTML解析以获取文本
我有一个HTML页面,其格式如下Python BeautifulSoup HTML解析以获取文本,python,html-parsing,beautifulsoup,Python,Html Parsing,Beautifulsoup,我有一个HTML页面,其格式如下 <section class="entry-content"> <p>...</p> <p>...</p> <p>...</p> </section> 您可以使用.stripped\u stringsiterable“深入”并从标记中获取文本: section = bs.find('section', {'class': 'entry-con
<section class="entry-content">
<p>...</p>
<p>...</p>
<p>...</p>
</section>
您可以使用
.stripped\u strings
iterable“深入”并从标记中获取文本:
section = bs.find('section', {'class': 'entry-content'})
ingreds = [' '.join(ch.stripped_strings) for ch in section.find_all(True)]
我们使用.find_all(True)
仅循环包含在部分
中的标记,而不是直接的文本内容(如换行符)
请注意,.find_all(True)
将遍历任何嵌套的标记,这可能会导致字符串重复。以下内容仅在部分的直接标记上循环:
ingreds = [' '.join(ch.stripped_strings) for ch in section if hasattr(ch, 'stripped_strings')]
我认为bs.find
可能返回NavigableString
和Tag
s的混合。只有标签
s将具有stripped_strings
属性。我只是想让你思考一下如何处理这个问题:如果我们有fooBAR
,那么将产生两次'BAR'
。您可以绕过这个问题,但我对必须使用isinstance
并不特别满意。你知道更好的方法吗?(我喜欢lxml+XPath,因为你不必对所有这些东西大惊小怪。)当我尝试这样做时,我得到一个错误:TypeError:“NoneType”对象不可调用
@ddroboul:你是否将None
分配给了.find_all()
或bs.find()
?@unutbu:Bah,骗子。好的,我将在部分进行循环
并使用if hasattr(ch,'stripped_strings')
。BeautifulSoup有它的缺陷,这是其中之一。
ingreds = [' '.join(ch.stripped_strings) for ch in section if hasattr(ch, 'stripped_strings')]