我在我的BeautifulSoup
代码中有一个调用find_all()
的语句。目前这个语句可以获取到所有的图片,但是如果我只想获取那些src
属性包含"placeholder"子字符串的图片,该怎么做呢?
for t in soup.find_all('img'): # WHERE img.href.contains("placeholder")
我在我的BeautifulSoup
代码中有一个调用find_all()
的语句。目前这个语句可以获取到所有的图片,但是如果我只想获取那些src
属性包含"placeholder"子字符串的图片,该怎么做呢?
for t in soup.find_all('img'): # WHERE img.href.contains("placeholder")
您可以在src
关键字参数中传递一个函数:(点击此处查看函数)
for t in soup.find_all('img', src=lambda x: x and 'placeholder' in x):
或者,一个正则表达式:
import re
for t in soup.find_all('img', src=re.compile(r'placeholder')):
或者,不使用find_all()
,而是使用select()
:
for t in soup.select('img[src*=placeholder]'):
soup.select('img[src*=placeholder]')
。 - Martijn Pieters
src
属性,而不是href
属性吧? - Martijn Pieters