您好,登錄后才能下訂單哦!
面對(duì)網(wǎng)絡(luò)不穩(wěn)定,頁(yè)面更新等問題,很可能出現(xiàn)程序異常的問題,所以我們要對(duì)程序進(jìn)行一些異常處理。大家可能覺得處理異常是一個(gè)比較麻煩的活,但在面對(duì)復(fù)雜網(wǎng)頁(yè)和任務(wù)的時(shí)候,無(wú)疑成為一個(gè)很好的代碼習(xí)慣。
網(wǎng)頁(yè)‘404'、‘500'等問題
try: html = urlopen('http://www.pmcaff.com/2221') except HTTPError as e: print(e)
返回的是空網(wǎng)頁(yè)
if html is None: print('沒有找到網(wǎng)頁(yè)')
目標(biāo)標(biāo)簽在網(wǎng)頁(yè)中缺失
try: #不存在的標(biāo)簽 content = bsObj.nonExistingTag.anotherTag except AttributeError as e: print('沒有找到你想要的標(biāo)簽') else: if content == None: print('沒有找到你想要的標(biāo)簽') else: print(content)
實(shí)例
if sys.version_info[0] == 2: from urllib2 import urlopen # Python 2 from urllib2 import HTTPError else: from urllib.request import urlopen # Python3 from urllib.error import HTTPError from bs4 import BeautifulSoup import sys def getTitle(url): try: html = urlopen(url) except HTTPError as e: print(e) return None try: bsObj = BeautifulSoup(html.read()) title = bsObj.body.h2 except AttributeError as e: return None return title title = getTitle("http://www.pythonscraping.com/exercises/exercise1.html") if title == None: print("Title could not be found") else: print(title)
以上全部為本篇文章的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。