在href标签中查找部分匹配项 [英] Finding partial matches in an href tag

查看:61
本文介绍了在href标签中查找部分匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Beautiful Soup查找所有<a>元素,其中href属性包括某个字符串.

I am trying to use Beautiful Soup to find all <a> elements where the href attribute includes a certain string.

完整元素的示例是:

<a href="/markets/NZSX/securities/ABA">ABA</a>

我正在寻找href包括"/markets/NZSX/securities/"的所有元素.

I am looking for all elements where href includes "/markets/NZSX/securities/".

我正在从此元素中提取文本.在示例中为ABA.

I am looking to extract the text from this element. This would be ABA in the example.

推荐答案

有几种方法可以实现.使用 .find_all() :

There are several ways to achieve that. With .find_all():

soup.find_all("a", href=re.compile(r"^/markets/NZSX/securities/"))
soup.find_all("a", href=lambda href: href and href.startswith("/markets/NZSX/securities/"))

或者,使用 CSS选择器:

Or, with a CSS selector:

soup.select('a[href^="/markets/NZSX/securities/"]')

以上内容将检查href是否以开头 /markets/NZSX/securities/.如果要改用包含"检查,则:

The above would check for the href to start with /markets/NZSX/securities/. If you want apply the "contains" check instead:

soup.find_all("a", href=re.compile(r"/markets/NZSX/securities/"))
soup.find_all("a", href=lambda href: href and "/markets/NZSX/securities/" in href)
soup.select('a[href*="/markets/NZSX/securities/"]')

这篇关于在href标签中查找部分匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆