如何使用beautifulsoup从div包围的范围中提取文本 [英] How to extract text from span surrounded by div using beautifulsoup
本文介绍了如何使用beautifulsoup从div包围的范围中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个html片段,如下所示:
I have a html snippet as below:
<div class="single_baby_name_description">
<label>Meaning :</label> <span class="28816-meaning">the meaning of this name is universal whole.</span> </br>
<label>Gender :</label> <span class="28816-gender">Girl</span> </br>
<label>Religion :</label> <span class="28816-religion">Christianity</span> </br>
<label>Origin :</label> <span class="28816-origin">German,French,Swedish</span> </br>
</div>
我尝试使用
soup = BeautifulSoup(html,'html.parser')
spans=soup.select('div.single_baby_name_description>span')
但是spans [0] .text仅从第一个标签获取文本.并且spans [1] .text发生IndexError:列表索引超出范围.
But spans[0].text gets only the text from the first tag . And spans[1].text occurs IndexError: list index out of range.
任何帮助将不胜感激.
推荐答案
我发现只有'lxml'可以胜任.由于某种原因,"html.parser"不会.
I found out that only 'lxml' will do the job. For some reason 'html.parser' won't.
这将起作用:
soup = BeautifulSoup(html, 'lxml')
spans = soup.select('div.single_baby_name_description span')
spans = [span.text for span in spans]
print(spans)
输出:
['the meaning of this name is universal whole.', 'Girl', 'Christianity', 'German,French,Swedish']
这篇关于如何使用beautifulsoup从div包围的范围中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文