码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-09-16 17:30:18      阅读:244      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!