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

How to check for tag contain specific attribute or not?

我想 从 content.but 中抓取 img 标签问题是一些 img 包含 data-src 和一些 containg src。

我试过以下方法:

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

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

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

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

它仍然不起作用我想抓取所有图像 url 其中包含 data-src 或 src 。

试试 lambda,像这样:

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

item.attrs 试试这个。

for item in content.select('img[itemprop="contentUrl"]'):
    if 'data-src' in item.attrs:
        print(item['data-src'])
    if 'src' in item.attrs:
        print(item['src'])

您可以使用 css 选择器或语法来收集 img 标签中任一属性的列表,然后使用嵌套的 .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)