Does BeautifulSoup find only those elements where the attribute contains a substring? Is it possible?

I have a call find_all()in my BeautifulSoupcode. This works now to get all the images, but if I wanted to direct only the images that have the "placeholder" substring in them src, how can I do this?

for t in soup.find_all('img'):  # WHERE img.href.contains("placeholder")
+4
source share
1 answer

You can pass a function in the keyword argument src:

for t in soup.find_all('img', src=lambda x: x and 'placeholder' in x):

Or, regex :

import re

for t in soup.find_all('img', src=re.compile(r'placeholder')):

Or find_all()use instead select():

for t in soup.select('img[src*=placeholder]'):
+10
source

All Articles