作为bs4的新手,我正在寻找一些帮助来解决如何从一系列网页表中提取文本的问题,其中一个是这样的:
<table style="padding:0px; margin:1px" width="715px">
<tr>
<td height="22" width="33%" >
<span class="darkGreenText"><strong> Name: </strong></span>
Tyto alba
</td>
<td height="22" width="33%" >
<span class="darkGreenText"><strong> Order: </strong></span>
Strigiformes
</td>
<td height="22" width="33%">
<span class="darkGreenText"><strong> Family: </strong></span>
Tytonidae
</td>
<td height="22" width="66%" colspan="2">
<span class="darkGreenText"><strong> Status: </strong></span>
Least Concern
</td>
</tr>
</table>
期望的输出:
Name: Tyto alba
Order: Strigiformes
Family: Tytonidae
Status: Least Concern
我已尝试按照建议使用[index]
(https://stackoverflow.com/a/35050622/1726290),
还有next_sibling
(https://stackoverflow.com/a/23380225/1726290)但是我被卡住了,因为我需要的文本的一部分被标记,而第二部分则没有。任何帮助将不胜感激。
答案 0 :(得分:1)
看起来你想要的是在BeautifulSoup标签上调用get_text(strip=True)
(docs)。假设raw_html
是你粘贴在上面的html:
htmlSoup = BeautifulSoup(raw_html)
for tag in htmlSoup.select('td'):
print(tag.get_text(strip=True))
打印:
Name:Tyto alba
Order:Strigiformes
Family:Tytonidae
Status:Least Concern