0
我收到此错误: requests.exceptions.MissingSchema:无效的URL'http:/1525/bg.png':没有提供模式。也许你的意思是http://http:/1525/bg.png?requests.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上) 感谢提前分配...
非常感谢。它工作(在try循环内移动请求) –
你好@ AT_1965不要忘记接受我的答案和任何答案,如果它为你工作。 – danidee
我回复了,“...非常感谢,它工作(在try循环中移动请求)”昨天。 –