Python BeautifulSoup find_all with regex与文本不匹配

2024-06-25 06:00:20 发布

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

我有以下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,但我仍然找不到问题。任何帮助都将不胜感激。谢谢


Tags: 代码textoutputhtmlallfindshopclass
2条回答

这里的问题是,您要查找的文本位于包含子标记的标记中,并且当标记包含子标记时,string属性为空

您可以在.find调用中使用lambda表达式,因为您正在查找固定字符串,所以可以仅使用'Shop' in t.text条件而不是正则表达式检查:

soup.find(lambda t: t.name == "a" and 'Shop' in t.text)

您正在搜索的文本Shop位于span标记内,因此当您尝试使用正则表达式时,它无法使用正则表达式获取值

您可以尝试使用正则表达式来查找文本,然后查找该文本的父级

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')
print(soup.find(text=re.compile('Shop')).parent.parent)

如果您有BS4.7.1或更高版本,您可以使用以下css选择器

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')
print(soup.select_one('a:contains("Shop")'))

相关问题 更多 >