繁体   English   中英

如何从网页下载图像?

[英]How to download images from the web page?

我有一个python脚本,可以在网页上搜索图像,并且应该将其下载到名为“ downloaded”的文件夹中。 最后2-3行存在问题,我不知道如何编写正确的“打开”代码。

脚本的最大部分很好,第42-43行给出了错误

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)

它会在我的计算机上打开下载的文件夹,并在其中打开其他文件夹。 并给出了回溯错误。 追溯:

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)

似乎您的downloadList包含一些不是图像的URL。 您可以改为在HTML中查找任何<img>标记:

downloadList = bsObj.find_all('img')

然后使用它下载那些图像:

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变量的常规约定是不使用驼峰式大小写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM