首页 > 解决方案 > Beautifulsoup - 为什么我正在抓取的图像没有保存?

问题描述

我遍历并从网站上抓取图像......但由于某种原因,“写入”无法正常工作并保存图像。我应该声明一个目录来保存它们吗?这是我的要求。我使用python 2.7

for img in imgs:
    image = img['href']
    img_url = my_url + image
    resource = urllib.urlretrieve(img_url)
    resource = resource[0]
    output = open(resource, "wb")
    output.write(resource)
    output.close()

标签: pythonbeautifulsoup

解决方案


你太辛苦了! urlretrieve已经将文件写入磁盘,您需要做的就是将其复制到更永久的位置。

filename,headers = urllib.urlretreive(img_url)
import shutil
shutil.copy(filename, "/path/to/somewhere")

但要回答你关于发生了什么的问题......

resource = urllib.urlretrieve(img_url) # the file is on disk at /tmp/foobar
resource = resource[0]   # resource now contains "/tmp/foobar"
output = open(resource, "wb")  # oops!  You just opened "/tmp/foobar" for writing, which clears the file



推荐阅读