Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取与特定属性值匹配的所有元素,但将任何标记或属性名称与BeautifulSoup匹配_Python_Beautifulsoup - Fatal编程技术网

Python 获取与特定属性值匹配的所有元素,但将任何标记或属性名称与BeautifulSoup匹配

Python 获取与特定属性值匹配的所有元素,但将任何标记或属性名称与BeautifulSoup匹配,python,beautifulsoup,Python,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.

是否可以获取与特定属性值匹配的所有元素,但将任何标记或属性名称与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}
,此示例将给出一些预期的结果。我正试图找出如何做到这一点,而不指定属性的名称,只匹配值。

您可以尝试无限制地查找\u 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表示有点接近,因此,您可以尝试无限制地查找所有标记,并过滤不符合您需要的标记

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表示有点接近

发布一个示例和可测试的html片段,并且output@RomanPerekhrest我已经修改了这个示例,所以它是可测试的,那么要匹配的值是什么?发布一个示例和可测试的html片段,期待output@RomanPerekhrest我已经修改了这个示例,所以它是可测试的,那么要匹配的值是什么?在理解中,如果文本在tag.attrs.values()中匹配,您也可以执行
,这看起来是一个很好的方法,可以让同样的事情发生,谢谢!在理解过程中,如果tag.attrs.values()中的文本与匹配,您也可以执行
这看起来是一个很好的方法,可以让同样的事情发生,谢谢!