Python脚本,使用BeautifulSoup将网站上的所有图像下载到指定的文件夹

时间:2018-06-27 18:55:30

标签: python image beautifulsoup request

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

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 似乎很好,但是如果我尝试使用 imgur heroimages 这样的其他网站,它似乎并没有工作。 如果我将网站声明替换为

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

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

另一方面,如果我将网站替换为

site = 'http://imgur.com'

我有时会得到

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

或者,如果确实下载了图像,由于出现以下错误,我什至无法打开它们: not supported file format

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

1 个答案:

答案 0 :(得分:3)

您需要等待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)
...