【发布时间】:2018-12-06 18:09:21
【问题描述】:
我找到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'
或者,如果图像确实下载,我什至无法打开它们,因为我收到以下错误:
另外值得注意的是,现在脚本要求目录指定的文件夹存在。我计划在将来更改它,以便脚本创建目录,如果它不存在的话。
【问题讨论】:
标签: python image beautifulsoup request