美化组以查找包含特定单词的链接

2024-06-11 08:34:19 发布

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

我有这个链接:

<a href="/location/santa-clara/3fce50c4f3f9793d2f503fc145585090">Santa Clara, California</a>

如何使用BeautifulSoup找到包含“location”一词的链接?


Tags: 链接locationsantahrefbeautifulsoupcaliforniaclara
1条回答
网友
1楼 · 发布于 2024-06-11 08:34:19

你可以用一个简单的"contains" CSS selector

soup.select("a[href*=location]")

或者,如果只需要匹配一个链接,请使用select_one()

soup.select_one("a[href*=location]")

当然,还有很多其他方法-例如,可以使用^{}提供href参数,该参数可以具有regular expression值或function

import re

soup.find_all("a", href=re.compile("location"))
soup.find_all("a", href=lambda href: href and "location" in href)

相关问题 更多 >