首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从网页下载图片?

如何从网页下载图片?
EN

Stack Overflow用户
提问于 2018-12-20 05:57:46
回答 1查看 59关注 0票数 0

我有一个在网页上搜索图像的python脚本,它应该将它们下载到名为“已下载”的文件夹中。最后2-3行是有问题的,我不知道如何写正确的“开放”代码。

脚本的最大部分没有问题,第42-43行给出了一个错误

代码语言:javascript
复制
import os
import requests
from bs4 import BeautifulSoup

downloadDirectory = "downloaded"
baseUrl = "http://pythonscraping.com"

def getAbsoluteURL(baseUrl, source):
    if source.startswith("http://www."):
        url = "http://"+source[11:]
    elif source.startswith("http://"):
        url = source
    elif source.startswith("www."):
        url = source[4:]
        url = "http://"+source
    else:
        url = baseUrl+"/"+source
    if baseUrl not in url:
        return None
    return url 

def getDownloadPath(baseUrl, absoluteUrl, downloadDirectory):
    path = absoluteUrl.replace("www.", "")
    path = path.replace(baseUrl, "")
    path = downloadDirectory+path
    directory = os.path.dirname(path)
    if not os.path.exists(directory):
        os.makedirs(directory)
    return path


html = requests.get("http://www.pythonscraping.com")
bsObj = BeautifulSoup(html.content, 'html.parser')
downloadList = bsObj.find_all(src=True)

for download in downloadList:
    fileUrl = getAbsoluteURL(baseUrl,download["src"])
    if fileUrl is not None:
        print(fileUrl)
    with open(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory), 'wb') as out_file:
        out_file.write(fileUrl.content)

它会打开我电脑上的已下载文件夹和其中的misc文件夹。它会给出一个回溯错误。回溯:

代码语言:javascript
复制
http://pythonscraping.com/misc/jquery.js?v=1.4.4
Traceback (most recent call last):
  File "C:\Python36\kodovi\downloaded.py", line 43, in <module>
    with open(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory), 'wb
') as out_file:
TypeError: an integer is required (got type str)
EN

回答 1

Stack Overflow用户

发布于 2018-12-20 06:07:51

看起来你的downloadList包含了一些不是图片的URL。相反,您可以在HTML中查找任何<img>标记:

代码语言:javascript
复制
downloadList = bsObj.find_all('img')

然后使用此命令下载这些图像:

代码语言:javascript
复制
for download in downloadList:
    fileUrl = getAbsoluteURL(baseUrl,download["src"])
    r = requests.get(fileUrl, allow_redirects=True)
    filename = os.path.join(downloadDirectory, fileUrl.split('/')[-1])
    open(filename, 'wb').write(r.content)

编辑:我已经更新了filename = ...行,以便它将同名文件写入字符串downloadDirectory中的目录。顺便说一下,Python变量的常规约定是不使用驼峰大小写。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53859707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档