【问题标题】:How to check for tag contain specific attribute or not?如何检查标签是否包含特定属性?
【发布时间】:2020-02-09 05:03:47
【问题描述】:

我想从内容中抓取 img 标签。但问题是一些 img 包含 data-src 和一些包含 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']

仍然无法正常工作,我想抓取包含 data-src 或 src 的所有图像 url。

【问题讨论】:

    标签: python beautifulsoup screen-scraping


    【解决方案1】:

    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'])
    

    【讨论】:

      【解决方案2】:

      尝试使用 lambda,如下所示:

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

      【讨论】:

        【解决方案3】:

        您可以使用 css 选择器或 sytax 来收集 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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-17
          • 2015-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-24
          • 1970-01-01
          相关资源
          最近更新 更多