2016-09-16 1 views
0

이 오류가 발생합니다 : requests.exceptions.MissingSchema : 잘못된 URL 'http : /1525/bg.png': 제공된 스키마가 없습니다. 아마도 http://http:/1525/bg.png을 의미할까요?requests.exceptions.MissingSchema : 잘못된 URL (bs4 포함)

오류가 발생한 이유에 대해 실제로 신경 쓰지는 않습니다. 유효하지 않은 URL 오류를 캡처하고 메시지를 발행하고 나머지 코드로 진행할 수 있기를 원합니다. 다음은

내가 그 특정 오류를 제외하고/시도 사용하려고 시도하지만 작동하지 않는거야 내 코드 ... 내 일을하지 무엇

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

입니까? (파이썬 3.5에 있습니다.) 미리 감사드립니다 ...

답변

0

오류에 대해 신경 쓰지 않는다면 (나쁜 프로그래밍이라고 생각합니다), 모든 예외를 포착하는 공백 예외 구문을 사용하십시오.

#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 블록 외부에서 발생하므로 (즉,이 경우의 try 블록에 requests.get를 이동하고 예외 처리가 작동합니다 때문입니다 당신은 여전히 ​​그것을 필요로합니다).

+0

고마워요. 그것은 작동했습니다 (시도 루프 내부 요청 이동) –

+0

안녕하세요 @ AT_1965 그것은 내 대답과 당신을 위해 일한 경우 어떤 대답을 받아들이는 것을 잊지 마세요. – danidee

+0

나는 회신을했다. .. "고마워. 어제 (시도 루프 안에서 요청을 움직였다)"어제. –