刮擦本地加载的图像

时间:2017-10-07 18:58:17

标签: python web web-scraping urllib

我正在努力学习Beautiful Soup,并且在尝试刮取从本地目录上传的图像时遇到了问题。我看到的错误是:

ValueError: unknown url type: 'images/ixa2.png'

我假设发生的事情是图像是从本地目录加载的,而不是通过URL托管的。当我检查我试图刮擦的元素时,这就是它的样子:

<img width="200" align="left" hspace="0" src="ixa/cards/axisofmortality.jpg">

我很好奇是否有可能刮掉这些图像,如果是的话,如何。

以下是我正在使用的代码:

from urllib import request
import urllib.request
from bs4 import BeautifulSoup as soup

def make_soup(url):
    result = request.urlopen(url)
    page = result.read()

    parsed_page = soup(page, "html.parser")
    result.close()
    return parsed_page

def get_images(url):
    soup = make_soup(url)
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + "images found.")
    print('Downloading images to current working directory.')
    #compile our unicode list of image links
    image_links = [each.get('src') for each in images]
    for each in image_links:
        filename=each.split('/')[-1]
        urllib.request.urlretrieve(each, filename)
    return image_links

get_images('http://mythicspoiler.com/')

1 个答案:

答案 0 :(得分:1)

您正在尝试从不完整的网址下载图片。

我的建议是这样的:

def get_images(url):
    soup = make_soup(url)
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + "images found.")
    print('Downloading images to current working directory.')
    #compile our unicode list of image links
    image_links = [each.get('src') for each in images]
    for each in image_links:
        filename=each.split('/')[-1]
        urllib.request.urlretrieve('http://mythicspoiler.com/' + each, filename) # <---
    return image_links