从包含br标记的td标记中提取文本

2024-04-20 03:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从包含br标签的td标签中提取文本。在

from bs4 import BeautifulSoup
html = "<td class=\"text\">This is <br/>a breakline<br/><br/></td>"
soup = BeautifulSoup(html, 'html.parser')
print(soup.td.string)

实际输出:None

预期输出:This is a breakline


Tags: textfrom文本brimportishtml标签
2条回答

来自美丽的汤document

If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None:

如果你想让文本部分document

If you only want the text part of a document or tag, you can use the get_text() method. It returns all the text in a document or beneath a tag, as a single Unicode string:

因此,您可以使用以下方法:

print(soup.get_text())

对于特定的标记soup.td.get_text()

这将为您提供您想要的:

print(soup.td.text)

这是针对特定的td标记的

否则,您还需要:

^{pr2}$

相关问题 更多 >