Python 如何检查标签是否包含特定属性?

Python 如何检查标签是否包含特定属性?,python,beautifulsoup,screen-scraping,Python,Beautifulsoup,Screen Scraping,我想从内容中删除img标签,但问题是一些img包含数据src,而另一些包含src 我尝试过以下方法: ifcontent.find'img',{'itemprop':'contentUrl'}['data-src']: image=content.find('img',{'itemprop':'contentUrl'})['data-src'] elifcontent.find'img',{'itemprop':'contentUrl'}['src']: image=content.find

我想从内容中删除img标签,但问题是一些img包含数据src,而另一些包含src

我尝试过以下方法:

ifcontent.find'img',{'itemprop':'contentUrl'}['data-src']:

image=content.find('img',{'itemprop':'contentUrl'})['data-src'] 
elifcontent.find'img',{'itemprop':'contentUrl'}['src']:

image=content.find('img',{'itemprop':'contentUrl'})['src']

但它仍然不起作用,我想清除所有包含数据src或src的图像url。

尝试使用lambda,类似以下内容:

img_l = lambda tag: (getattr(tag, "name") == "img" and "src" in tag.attrs)
images = content.find_all(img_l)    

试试lambda,类似这样的:

img_l = lambda tag: (getattr(tag, "name") == "img" and "src" in tag.attrs)
images = content.find_all(img_l)    
使用item.attrs尝试此操作

使用item.attrs尝试此操作


您可以使用css选择器或sytax来收集img标记中任一属性的列表,然后使用nested.get

from bs4 import BeautifulSoup as bs

html = '''
<img src="mePlease.gif" alt="Yey" height="42" width="42">
<img data-src="me2.gif" alt="Yey" height="42" width="42">
'''
soup = bs(html, 'lxml')
attrs = [i.get('src', i.get('data-src', None)) for i in soup.select('img[src],img[data-src]')]
print(attrs)

您可以使用css选择器或sytax来收集img标记中任一属性的列表,然后使用nested.get

from bs4 import BeautifulSoup as bs

html = '''
<img src="mePlease.gif" alt="Yey" height="42" width="42">
<img data-src="me2.gif" alt="Yey" height="42" width="42">
'''
soup = bs(html, 'lxml')
attrs = [i.get('src', i.get('data-src', None)) for i in soup.select('img[src],img[data-src]')]
print(attrs)