是否可以使用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}
,则本示例将获得预期的结果。我试图弄清楚如何在不指定属性名称的情况下执行此操作,而仅与值匹配。
答案 0 :(得分:2)
您可以尝试无限制的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表示形式