【问题标题】:Getting text without tags using BeautifulSoup?使用 BeautifulSoup 获取没有标签的文本?
【发布时间】:2015-08-29 18:38:34
【问题描述】:
我一直在使用 BeautifulSoup 解析 HTML 文档,但似乎遇到了问题。我发现了一些需要提取的文本,但文本很简单。没有标签或任何东西。我不确定是否需要使用 Regex 来执行此操作,因为我不知道是否可以使用 BeautifulSoup 抓取文本,因为它不包含任何标签。
<strike style="color: #777777">975</strike> 487 RP<div class="gs-container default-2-col">
我正在尝试提取“487”。
谢谢!
【问题讨论】:
标签:
python
html
regex
parsing
beautifulsoup
【解决方案1】:
您可以使用上一个或下一个标签作为锚点来查找文本。比如先找到<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
请注意,上面的代码是为了演示,而不是完成你的整个任务。