【发布时间】:2020-08-14 22:16:47
【问题描述】:
我有以下 HTML 代码:
<a class="nav-link" href="https://cbd420.ch/fr/tous-les-produits/">
<span class="cbp-tab-title">
Shop <i class="fa fa-angle-down cbp-submenu-aindicator"></i></span>
</a>
我想获取具有Shop 的锚标记作为文本,而不考虑前后的间距。我已经尝试了以下代码,但我一直得到一个空数组:
import re
html = """<a class="nav-link" href="https://cbd420.ch/fr/tous-les-produits/">
<span class="cbp-tab-title">
Shop <i class="fa fa-angle-down cbp-submenu-aindicator"></i></span>
</a>"""
soup = BeautifulSoup(html, 'html.parser')
prog = re.compile('\s*Shop\s*')
print(soup.find_all("a", string=prog))
# Output: []
我还尝试使用 get_text() 检索文本:
text = soup.find_all("a")[0].get_text()
print(repr(text))
# Output: '\n\n\t\t\t\t\t\t\t\tShop \n'
并运行以下代码以确保我的正则表达式是正确的,这似乎是这种情况。
result = prog.match(text)
print(repr(result.group()))
# Output: '\n\n\t\t\t\t\t\t\t\tShop \n'
我也尝试选择span 而不是a,但我遇到了同样的问题。我猜这是find_all 的问题,我已经阅读了BeautifulSoup documentation,但我仍然找不到问题。任何帮助,将不胜感激。谢谢!
【问题讨论】:
-
试试
soup.find(lambda t: t.name == "a" and 'Shop' in t.text) -
哇!谢谢。知道为什么它不适用于正则表达式吗? @WiktorStribiżew
标签: python html regex beautifulsoup re