首页 > 解决方案 > 使用 BeautifulSoup 将所有图像从网站下载到指定文件夹的 Python 脚本

问题描述

我找到了这篇文章并想稍微修改脚本以将图像下载到特定文件夹。我编辑的文件如下所示:

import re
import requests
from bs4 import BeautifulSoup
import os

site = 'http://pixabay.com'
directory = "pixabay/" #Relative to script location

response = requests.get(site)

soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]

for url in urls:
    #print(url)
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)

    with open(os.path.join(directory, filename.group(1)), 'wb') as f:
        if 'http' not in url:
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)

这似乎适用于pixabay,但如果我尝试不同的网站,如imgurheroimages,它似乎不起作用。如果我将站点声明替换为

site = 'http://heroimages.com/portfolio'

什么都没有下载。打印语句(未注释时)不打印任何内容,所以我猜它没有找到任何图像标签?我不知道。

另一方面,如果我用

site = 'http://imgur.com'

我有时会得到一个

AttributeError: 'NoneType' object has no attribute 'group'

或者,如果图像确实下载,我什至无法打开它们,因为我收到以下错误: 不支持的文件格式

另外值得注意的是,现在脚本需要目录指定的文件夹存在。我计划在将来更改它,以便脚本创建目录,如果它不存在的话。

标签: pythonimagebeautifulsouprequest

解决方案


您需要等待 javascript 加载页面,我认为这是问题所在,如果您愿意,可以使用selenium

# your imports
...
from selenium import webdriver

site = 'http://heroimages.com/portfolio'
directory = "pixabay/" #Relative to script location

driver = webdriver.Chrome('/usr/local/bin/chromedriver')

driver.get(site)

soup = BeautifulSoup(driver.page_source, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]

for url in urls:
    print(url)
    # your code
    ...

输出

# from `http://heroimages.com/portfolio`
https://ssl.c.photoshelter.com/img-get2/I00004gQScPHUm5I/sec=wdtsdfoeflwefms1440ed201806304risXP3bS2xDXil/fill=350x233/361-03112.jpg
https://ssl.c.photoshelter.com/img-get2/I0000h9YWTlnCxXY/sec=wdtsdfoeflwefms1440ed20180630Nq90zU4qg6ukT5K/fill=350x233/378-01449.jpg
https://ssl.c.photoshelter.com/img-get2/I0000HNg_JtT_QrQ/sec=wdtsdfoeflwefms1440ed201806304CZwwO1L641maB9/fill=350x233/238-1027-hro-3552.jpg
https://ssl.c.photoshelter.com/img-get2/I00000LWwYspqXuk/sec=wdtsdfoeflwefms1440ed201806302BP_NaDsGb7udq0/fill=350x233/258-02351.jpg
# and many others images

还有检查目录是否存在的脚本,如果不存在则创建它。

...
directory = os.path.dirname(os.path.realpath(__file__)) + '/pixabay/'    
if not os.path.exists(directory):
    os.makedirs(directory)
...                  

推荐阅读