2017-02-14 41 views
0

我正在嘗試此代碼,因爲我正在學習如何從網站上廢棄所有圖像。這是我從書中獲得的代碼,該程序能夠順利運行而沒有任何錯誤,但問題在於,在運行代碼之後,沒有任何圖像保存在文件夾「xkcd」中。我已經仔細觀察了好幾個小時,但我仍然無法弄清楚,所以想要就我忽視的內容尋求幫助。任何援助非常感謝。Python - 文件寫入後未保存

import requests, os, bs4 

url = 'http://xkcd.com'    # starting url 
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd 
while not url.endswith('1790/'): 
# Download the page. 
print('Downloading page %s...' % url) 
res = requests.get(url) 
res.raise_for_status() 

soup = bs4.BeautifulSoup(res.text,'html.parser') 
# Find the URL of the comic image. 
comicElem = soup.select('#comic img') 

if comicElem == []: 
    print('Could not find comic image.') 
else: 
    try: 
     comicUrl = 'http:' + comicElem[0].get('src') 
     # Download the image. 
     print('Downloading image %s...' % (comicUrl)) 
     res = requests.get(comicUrl) 
     res.raise_for_status() 

    except requests.exceptions.MissingSchema: 
     # skip this comic 
     prevLink = soup.select('a[rel="prev"]')[0] 
     url = 'http://xkcd.com' + prevLink.get('href') 
     continue 
    # Save the image to ./xkcd. 
    imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') 
    for chunk in res.iter_content(100000): 
     imageFile.write(chunk) 
     imageFile.close() 

# Get the Prev button's url. 
prevLink = soup.select('a[rel="prev"]')[0] 
url = 'http://xkcd.com' + prevLink.get('href') 
print('Done.') 

編輯:上面的代碼現在運行良好。

+0

我不確定你的格式是否正確; 「continue」語句運行後沒有任何內容可以保存 – Dillanm

+0

您可以檢查縮進嗎?現在你的文件寫入在你的異常處理和'繼續'之後。 – JCVanHamme

+0

如果此代碼與您正在運行的代碼相同,則僅在發生'MissingSchema'異常時纔會保存文件。你必須將其移出'except'塊。 – JCVanHamme

回答

0

if或許應該閱讀:

if comicElem == []: 
    print('Could not find comic image.') 
else: 
    try: 
     comicUrl = 'http:' + comicElem[0].get('src') 
     # Download the image. 
     print('Downloading image %s...' % (comicUrl)) 
     res = requests.get(comicUrl) 
     res.raise_for_status() 

     # Save the image to ./xkcd. 
     imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') 
     for chunk in res.iter_content(100000): 
     imageFile.write(chunk) 
     imageFile.close() 

    except requests.exceptions.MissingSchema: 
     # skip this comic 
     prevLink = soup.select('a[rel="prev"]')[0] 
     url = 'http://xkcd.com' + prevLink.get('href') 
     continue 

我不完全知道爲什麼你試圖挽救一個異常處理程序中的文件,但無論是「繼續」聲明將意味着,實際的保存代碼從未正在運行。

0

你的寫作操作應該在try塊內。