使用Pillow的Image.save()函数在尝试使用Splinter从页面下载图像时抛出AttributeError

时间:2014-10-15 09:28:40

标签: python web-scraping attributeerror pillow splinter

我正在尝试使用Splinter浏览器库(使用ChromeDriver)和Pillow库从网页下载图像。我使用Chrome浏览器的一个实例登录网站,然后导航到包含图片的页面,然后使用browser.find_by_tag()方法找到图片。

然后我尝试使用Pillow的Image.save()方法,但它会抛出此错误:

C:\Users\my.name\Documents\Development\Python-Scripts>my_script.py
Traceback (most recent call last):
  File "C:\Users\my.name\Documents\Development\Python-Scripts\my_script.p
y", line 31, in <module>
    my_function()
  File "C:\Users\my.name\Documents\Development\Python-Scripts\my_script.p
y", line 19, in my_function
    farmer_image = Image.save(farmer_image_brobj)
AttributeError: 'module' object has no attribute 'save'

我的代码:

from splinter import Browser
from PIL import Image

def my_function():
    with Browser('chrome') as browser: 
        url = "http://www.blah/login.aspx"
        url_two = "http://www.blah/ImagePageParent.aspx"

        browser.visit(url)
        browser.fill('un', 'blah')
        browser.fill('pw', 'blah')
        browser.find_by_name('btn').click()
        browser.visit(url_two)
        browser.find_link_by_partial_href('partial_href').click() 

        farmer_image_brobj = browser.find_by_tag('img')
        farmer_image = Image.save(farmer_image_brobj)

        browser.visit(url_two)
        browser.quit()

my_function()

1 个答案:

答案 0 :(得分:1)

effbot example开始,你的方式是错误的。而不是

    farmer_image_brobj = browser.find_by_tag('img')
    farmer_image = Image.save(farmer_image_brobj)

您应该在Image实例上使用save()方法。首先,打开图像:

farmer_imag = Image.open(...) #something doing with farmer_image_brobj
例如,使用请求,您可以执行以下操作:

r = requests.get('http://example.com/image.jpg')
farmer_image = Image.open(StringIO(r.content))

然后通过提供路径保存它:

farmer_image.save('my_image.png')