如何从网页下载图像?

时间:2018-12-19 21:57:46

标签: python image web-scraping

我有一个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)

1 个答案:

答案 0 :(得分:0)

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