python - 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()
解决方案
你太辛苦了! 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
推荐阅读
- php - 通过 Junction Table yii2 的相关模型
- codenameone - 使用 Object-C 本机接口时的代号一“内存不足”(HEIC 到 JPEG 转换)
- google-bigquery - 更改现有 bigquery 表中的聚集列
- html - 如何单独设置标题并将图片放在两侧并添加社交媒体图标并将其居中
- scala - 从案例类中获取所有实体并将它们转换为字符串
- javascript - 获取嵌套数组Javascript的元素
- java - RestController 自动填充请求正文和标头
- database - 有没有办法用内存引擎删除clickhouse表上的所有数据?
- tensorflow - Tensorflow:为什么直接训练模型和参数有差异
- javascript - 对象如何包含函数保存