使用 BeautifulSoup 获取不带标签的文本?

Getting text without tags using BeautifulSoup?

我一直在使用 BeautifulSoup 解析 HTML 文档,但似乎 运行 遇到了问题。我找到了一些需要提取的文本,但文本很普通。没有标签或任何东西。我不确定我是否需要使用 Regex 来代替,因为我不知道我是否可以使用 BeautifulSoup 获取文本,因为它不包含任何标签。

<strike style="color: #777777">975</strike> 487 RP<div class="gs-container default-2-col">

我正在尝试提取“487”。

谢谢!

您可以使用上一个或下一个标签作为锚点来查找文本。比如先找到<strike>元素,然后得到它旁边的文本节点:

from bs4 import BeautifulSoup

html = """<strike style="color: #777777">975</strike> 487 RP<div class="gs-container default-2-col">"""
soup = BeautifulSoup(html)

#find <strike> element first, then get text element next to it
result = soup.find('strike',{'style': 'color: #777777'}).findNextSibling(text=True)

print(result.encode('utf-8'))
#output : ' 487 RP' 
#you can then do simple text manipulation/regex to clean up the result

请注意,以上代码只是为了演示,并不是为了完成您的全部任务。