2016-07-14 2 views
-4

Я написал сценарий для загрузки одного изображения с сайта xkcd comics. Но сценарий обычно запускается и не загружает изображения. В чем проблема ? Любая помощь будет оценена по достоинству. Вот код:Не удается загрузить изображение через скрипт python

#! python3 


import requests, os, bs4 

url = 'http://xkcd.com' # starting rule 
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd 

    # Download the page 
print('Downloading the page %s...' % url) 
res = requests.get(url) 
res.raise_for_status() 

soup = bs4.BeautifulSoup(res.text) 

# 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() 

print('Done.') 
+0

Просьба предоставить соответствующий фрагмент HTML, который включает в себя 'a' для изображения, которое вы хотите загрузить. –

ответ

0

Ваша проблема заключается в том, что вы сохраняете изображение в своем блоке исключений, отступая от него. Более простой способ загрузки файлового объекта - использовать shutal.

import requests, os, bs4, shutil 

url = 'http://xkcd.com' # starting rule 
if not os.path.exists('xkcd'): 
    os.makedirs('xkcd') # store comics in ./xkcd 

    # Download the page 
print('Downloading the page %s...' % url) 
res = requests.get(url) 
res.raise_for_status() 

soup = bs4.BeautifulSoup(res.text) 

# Find the URL of the comic image 
comicElem = soup.select('#comic img') 
if comicElem == []: 
    print('Could not find comic image.') 
else: 
    comicURL = "http:"+comicElem[0].get('src') 
    response = requests.get(comicURL, stream=True) 
    with open('xkcd/img.png', 'wb') as out_file: 
     shutil.copyfileobj(response.raw, out_file) 
    del response 



print('Done.') 
Смежные вопросы