首页 > 编程语言 > 详细

Python网络爬虫 - 3. 异常处理

时间:2015-09-16 17:27:05      阅读:295      评论:0      收藏:0      [点我收藏+]

handle_excpetion.py

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import sys


def getLogo(url):
    try:
        html = urlopen(url)
    except HTTPError as e:
        print("url open exception:")
        print(e)
        return None
    
    try:
        bsObj = BeautifulSoup(html.read(), "html.parser")
        logo = bsObj.body.img
    except AttributeError as e:
        print("parse logo exception:")
        print(e)
        return None
    return logo

logo = getLogo("http://www.baidu2.com/nopage.html")
if logo == None:
    print("Logo could not be found")
else:
    print(logo)
    
    

 

运行结果:


url open exception:
HTTP Error 404: Not Found
Logo could not be found

 

Python网络爬虫 - 3. 异常处理

原文:http://www.cnblogs.com/davidgu/p/4813567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!