【问题标题】:Crawl and download png and jpegs抓取和下载 png 和 jpeg
【发布时间】:2018-11-16 16:52:18
【问题描述】:

我想抓取任何网站并只下载图片。但是,使用以下代码,程序甚至可以下载 img 标签中存在的 gif。如何选择只下载 png 和 jpeg?

def fetch_url():
    url = _url.get()
    config['images'] = []
    _images.set(())
try:
    page = requests.get(url)
except requests.RequestException as rex:
    _sb(str(rex))
else:
    soup = BeautifulSoup(page.content, 'html.parser')
    images = fetch_images(soup, url)
    if images:
        _images.set(tuple(img['name'] for img in images))
        _sb('Images found: {}'.format(len(images)))
    else:
        _sb('No images found!.')
    config['images'] = images


def fetch_images(soup, base_url):
    images = []
    for img in soup.findAll('img'):
        src = img.get('src')
        img_url = ('{base_url}/{src}'.format(base_url=base_url, src=src))
        name = img_url.split('/')[-1]
        images.append(dict(name=name, url=img_url))
    return images

【问题讨论】:

  • install wget.. 当你想下载图片时,它是一个很棒的工具。

标签: python web-scraping beautifulsoup web-crawler


【解决方案1】:

您是否尝试仅附加您想要的格式?

def fetch_images(soup, base_url):
    images = []
    for img in soup.findAll('img'):
       src = img.get('src')
       img_url = ('{base_url}/{src}'.format(base_url=base_url, src=src))
       name = img_url.split('/')[-1]
       if name[-3:] == "png" or name[-3:] == "jpg" or name[-4:] == "jpeg": ### <- here
           images.append(dict(name=name, url=img_url))
    return images

【讨论】:

    【解决方案2】:

    我会寻找以.jpeg.png 结尾的href

    soup.select("[href$='.png'], [href$='.jpeg']")
    

    【讨论】:

      【解决方案3】:

      您也可以在查找标签时使用正则表达式。

      from bs4 import BeautifulSoup
      import re
      html = """
      <html>
        <body>
          <img src="dav.jpg">
          <img src="dav.jpeg">
          <img src="dav.png">
          <img src="dav.pdf"><p>
        </body>
      </html>
      
      """
      
      soup = BeautifulSoup(html,"lxml")
      print( soup.find_all("img",src=re.compile(r".*?(?=jpeg|png)")))
      # [<img src="dav.jpeg"/>, <img src="dav.png"/>]
      

      【讨论】:

        猜你喜欢
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 2018-10-21
        • 2012-08-16
        • 2018-09-12
        • 2010-10-16
        • 2020-12-26
        • 2014-04-22
        相关资源
        最近更新 更多