2016-09-16 225 views
0

我收到此错误: requests.exceptions.MissingSchema:无效的URL'http:/1525/bg.png':没有提供模式。也许你的意思是http://http:/1525/bg.pngrequests.exceptions.MissingSchema:无效的URL(带有bs4)

我不在乎为什么发生错误,我希望能够捕获任何无效的URL错误,发出消息并继续执行其余的代码。

下面是我的代码,在那里我试图使用try /除外具体错误,但它不工作...

# load xkcd page 
# save comic image on that page 
# follow <previous> comic link 
# repeat until last comic is reached 

import webbrowser, bs4, os, requests 

url = 'http://xkcd.com/1526/' 
os.makedirs('xkcd', exist_ok=True) 

while not url.endswith('#'): # - last page 

    # download the page 
    print('Dowloading page %s...' % (url)) 
    res = requests.get(url) 
    res.raise_for_status() 
    soup = bs4.BeautifulSoup(res.text, "html.parser") 

    # find url of the comic image (<div id ="comic"><img src="........" 
    </div 
    comicElem = soup.select('#comic img') 
    if comicElem == []: 
     print('Could not find any images') 
    else: 
     comicUrl = 'http:' + comicElem[0].get('src') 

     #download the image 
     print('Downloading image... %s' % (comicUrl)) 
     res = requests.get(comicUrl) 
     try: 
      res.raise_for_status() 
     except requests.exceptions.MissingSchema as err: 
      print(err) 
      continue 

     # save image to folder 
     imageFile = open(os.path.join('xkcd', 
     os.path.basename(comicUrl)), 'wb') 
     for chunk in res.iter_content(1000000): 
      imageFile.write(chunk) 
     imageFile.close() 

#get <previous> button url 
prevLink = soup.select('a[rel="prev"]')[0] 
url = 'http://xkcd.com' + prevLink.get('href') 

print('Done') 

我没有做什么? (我在python 3.5上) 感谢提前分配...

回答

0

如果你不关心错误(我认为是不好的编程),只需使用一个空白的except语句来捕获所有异常。

#download the image 
print('Downloading image... %s' % (comicUrl)) 
try: 
    res = requests.get(comicUrl) # moved inside the try block 
    res.raise_for_status() 
except: 
    continue 

但另一方面,如果只是块你不捕捉异常则是因为异常实际发生的try块外面,所以移动requests.get到try块和异常处理应该工作(也就是如果你仍然需要它)。

+0

非常感谢。它工作(在try循环内移动请求) –

+0

你好@ AT_1965不要忘记接受我的答案和任何答案,如果它为你工作。 – danidee

+0

我回复了,“...非常感谢,它工作(在try循环中移动请求)”昨天。 –