处理地址异常

xiaoxiao2021-02-27  137

from urllib.request import urlopen from urllib.error import HTTPError,URLError from bs4 import BeautifulSoup ''' 如果想用HTTPError和URLError一起捕获异常,那么需要将HTTPError放在URLError的前面, 因为HTTPError是URLError的一个子类。如果URLError放在前面,出现HTTP异常会先响应URLError, 这样HTTPError就捕获不到错误信息了 ''' def getTitle(url): try: html = urlopen(url) except HTTPError as e: print('HTTPError:%s'%e.code) return None except URLError as e: print('URLError:%s'%e.code) try: bsObj = BeautifulSoup(html,'html.parser') title = bsObj.body.h12 import pdb pdb.set_trace() except AttributeError as e: print('AttributeError:%s'%e.code) return None print('1') return title title = getTitle("http://www.pythonscraping.com/pages/page1.html") if title == None: print("Title could not be found") else: print(title)
转载请注明原文地址: https://www.6miu.com/read-12948.html

最新回复(0)