2014-04-17 44 views
0

我是Python的新手,似乎無法獲取圖像下載並保存到文件。我想知道是否有人能指出我的錯誤。我以各種方式嘗試了兩種方法無濟於事。這裏是我的代碼如下:Python:無法將圖像下載/保存到文件

# Ask user to enter URL 
url= http://hosted.ap.org/dynamic/stories/A/AF_PISTORIUS_TRIAL?SITE=AP&SECTION=HOME&TEMPLATE=DEFAULT&CTIME=2014-04-15-15-48-52 

timestamp = datetime.date.today() 

soup = BeautifulSoup(urllib2.urlopen(url).read()) 
#soup = BeautifulSoup(requests.get(url).text) 

# ap 
links = soup.find("td", {'class': 'ap-mediabox-td'}).find_all('img', src=True) 
for link in links: 
    imgfile = open('%s.jpg' % timestamp, "wb") 
    link = link["src"].split("src=")[-1] 
    imgurl = "http://hosted.ap.org/dynamic/files" + link 
    download_img = urllib2.urlopen(imgurl).read() 
    #download_img = requests.get(imgurl, stream=True) 
    #imgfile.write(download_img.content) 
    imgfile.write(download_img) 
    imgfile.close() 

    # link outputs: /photos/F/f5cc6144-d991-4e28-b5e6-acc0badcea56-small.jpg 
    # imgurl outputs: http://hosted.ap.org/dynamic/files/photos/F/f5cc6144-d991-4e28-b5e6-acc0badcea56-small.jpg 

我收到沒有控制檯錯誤,只是一個空的圖片文件。

回答

0

圖像的相對路徑可以簡單地通過做來獲得:

link = link["src"] 

你聲明:

link = link["src"].split("src=")[-1] 

過大。用上面的替換它,你應該得到創建的圖像文件。當我試用它時,我可以創建圖像文件。但是,我無法查看圖像。它說,圖像已損壞。

我不得不這樣做使用Python的requests庫使用此代碼段相同的任務,在過去的成功:在片段

r = requests.get(url, stream=True) 
     if r.status_code == 200: 
      with open('photo.jpg', 'wb') as f: 
       for chunk in r.iter_content(): 
        f.write(chunk) 
      f.close() 

url上面會計算與我在開始時建議改變你的imgurl

希望這會有所幫助。

+0

不幸的是沒有工作。我以前嘗試過使用請求。仍然得到圖像損壞的結果。任何想法可能會造成這種情況? – user3285763