Python FTP抓取和保存图片问题
编辑:我搞定了,但就是下载不了任何东西...
这是我简化后的代码:
notions_ftp = ftplib.FTP(ftp_host, ftp_user, ftp_passwd)
folder = "Leisure Arts - Images"
notions_ftp.cwd(folder)
image = open("015693PR-com.jpg","wb")
notions_ftp.retrlines("RETR 015693PR-com.jpg", image.write)
send_image = open("015693PR-com.jpg", 'r')
这是我的输出:
'250 "/Leisure Arts - Images": is current directory.'
'226 Transfer complete. 0 bytes in 0.00 sec. (0.000 Kb/s)'
原帖:好吧,我今天一直在折腾这个。我对Python的FTP还比较陌生。所以我在这里搜索了一下,得到了这个:
images = notions_ftp.nlst()
for image_name in image_names:
if found_url == False:
try:
for image in images:
ftp_image_name = "./%s" % image_name
if ftp_image_name == image:
found_url = True
image_name_we_want = image_name
except:
pass
# We failed to find an image for this product, it will have to be done manually
if found_url == False:
log.info("Image ain't there baby -- SKU: %s" % sku)
return False
# Hey we found something! Open the image....
notions_ftp.retrlines("RETR %s" % image_name_we_want, open(image_name_we_want, "rb"))
1/0
我把错误缩小到在我除以零之前的那一行。这里是错误信息:
Traceback (most recent call last):
File "<console>", line 6, in <module>
File "<console>", line 39, in insert_image
IOError: [Errno 2] No such file or directory: '411483CC-IT,IM.jpg'
如果你跟着代码走,你会看到图片确实在目录里,因为如果在我代码的第一行找到,就会设置image_name_we_want。我知道它在那儿,因为我自己在看FTP网站,...它确实在那儿。所以在这一切过程中,我曾经成功把图片保存到本地,这是我最想要的,但我早就忘了我是怎么做到的。不管怎样,为什么它会认为图片不在那儿,而实际上在列表中找到了呢。
好吧,我采纳了建议,现在我得到了:
14:01:18,057 ERROR [pylons-admin] Image to big or corrupt! Skipping Image for product sku: 411483
14:01:18,057 ERROR [pylons-admin] Image to big or corrupt! Skipping Image for product sku: 411483
Traceback (most recent call last):
File "<console>", line 6, in <module>
File "<console>", line 40, in insert_image
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ftplib.py", line 418, in retrlines
callback(line)
TypeError: 'file' object is not callable
>>> 14:01:24,694 INFO [pylons-admin] Script Done! Updated 0 Products w/ Images
它成功获取了第一张图片,我觉得那张真的有问题,但当它继续处理下一张时,就在文件对象上抛出了那个错误。所以这是我怎么改的,以及其余的代码在这里没有放出来:
# Hey we found something! Open the image....
f = open(image_name_we_want, "wb")
notions_ftp.retrlines("RETR %s" % image_name_we_want, f)
send_image = open(image_name_we_want, 'r')
# ...and send it for processing
try:
image_id = product_obj.set_image(send_image, 5, 1)
except IOError, error:
log.error("Image to big or corrupt! Skipping Image for product sku: %s" % sku)
image_id = False
else:
if image_id == False:
log.error("Could not Insert the image for product sku: %s" % sku)
f.close()
return False
else:
f.close()
os.remove(image_name_we_want)
return True
1 个回答
1
你现在是在读取文件,而不是写入文件。
所以,应该把 open(image_name_we_want, "rb")
改成 open(image_name_we_want, "wb")
。
[编辑]
如果你只是从ftp服务器上获取文件,你也可以试试这个:
import urllib2
fh = urllib2.urlopen('ftp://server/path/file.png')
file('file.png', 'wb').write(fh.read())
另外,如果想要一个完整的示例,可以看看这个链接: http://docs.python.org/library/ftplib.html
你还缺少在 open()
后面的 write
。