我试图从这个html标记中获取所有文本,并将其存储在变量tag中:

<td rowspan="2" style="text-align: center;"><a href="/wiki/Glenn_Miller" title="Glenn Miller">Glenn Miller</a> &amp; His Orchestra</td>

结果应该是"Glenn Miller & His Orchestra"
但是ing返回这个:print
如何获取tag.find(text=True)元素中的其余文本?

最佳答案

tag.find(text=True)将返回第一个匹配的文本节点。使用.get_text()代替:

>>> from bs4 import BeautifulSoup
>>> data = '<td rowspan="2" style="text-align: center;"><a href="/wiki/Glenn_Miller" title="Glenn Miller">Glenn Miller</a> &amp; His Orchestra</td>'
>>> soup = BeautifulSoup(data, "html.parser")
>>> tag = soup.td
>>> tag.get_text()
'Glenn Miller & His Orchestra'

10-06 08:49