BeautifulSoup找到包含特定单词的链接

Mor*_*len 7 python beautifulsoup

我有这个链接:

__CODE__

我如何使用BeautifulSoup专门找到包含单词location"location"的链接?

ale*_*cxe 25

你可以用一个简单的"包含"CSS选择器来做到这一点:

soup.select("a[href*=location]")
Run Code Online (Sandbox Code Playgroud)

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

soup.select_one("a[href*=location]")
Run Code Online (Sandbox Code Playgroud)

当然,还有很多其他方法 - 例如,您可以使用find_all()提供href可以具有正则表达式值或函数的参数:

import re

soup.find_all("a", href=re.compile("location"))
soup.find_all("a", href=lambda href: href and "location" in href)
Run Code Online (Sandbox Code Playgroud)

  • 选择器需要在要搜索的字符串周围加上引号。即:`soup.select("a[href*='location']")` 表示'包含',`soup.select("a[href^='location']")` 表示'开始于'。另外:请注意 Padraic Cunningham 的评论中的轻微拼写错误(缺少“f”)。谢谢! (3认同)
  • 或者``soup.select_one("[[hre ^ =/location]")`如果你想要以/ location开头的hrefs (2认同)