首页 > 解决方案 > 获取与特定属性值匹配但与 BeautifulSoup 匹配的任何标签或属性名称的所有元素

问题描述

是否可以获取与特定属性值匹配但与 BeautifulSoup 匹配的任何标签或属性名称的所有元素。如果是这样,有人知道该怎么做吗?

这是我尝试做的一个例子

from bs4 import BeautifulSoup
import requests

text_to_match = 'https://s3-ap-southeast-2.amazonaws.com/bettss3/images/003obzt0t_w1200_h1200.jpg'
url = 'https://www.betts.com.au/item/37510-command.html?colour=chocolate'
r = requests.get(url)
bs = BeautifulSoup(r.text, features="html.parser")
possibles = bs.find_all(None, {None: text_to_match})
print(possibles)

这给了我一个空列表[]。

如果我{None: text_to_match}{'href': text_to_match}这个例子替换会得到一些预期的结果。我试图弄清楚如何在不指定属性名称且仅匹配值的情况下执行此操作。

标签: pythonbeautifulsoup

解决方案


您可以尝试无限制地 find_all 并过滤那些不符合您需求的人,例如

text_to_match = 'https://s3-ap-southeast-2.amazonaws.com/bettss3/images/003obzt0t_w1200_h1200.jpg'
url = 'https://www.betts.com.au/item/37510-command.html?colour=chocolate'
r = requests.get(url)
bs = BeautifulSoup(r.text, features="html.parser")
tags = [tag for tag in bs.find_all() if text_to_match in str(tag)]
print(tags)

这种解决方案有点笨拙,因为您可能会得到一些不相关的标签,您可以通过以下方式使您的文本更具标签特定性:

text_to_match = r'="https://s3-ap-southeast-2.amazonaws.com/bettss3/images/003obzt0t_w1200_h1200.jpg"'

这更接近于带有属性的标签的 str 表示


推荐阅读