Python爬虫包BeautifulSoup异常处理(二)

yipeiwu_com6年前Python爬虫

面对网络不稳定,页面更新等问题,很可能出现程序异常的问题,所以我们要对程序进行一些异常处理。大家可能觉得处理异常是一个比较麻烦的活,但在面对复杂网页和任务的时候,无疑成为一个很好的代码习惯。

网页‘404'、‘500'等问题

try:
    html = urlopen('http://www.pmcaff.com/2221')
  except HTTPError as e:
    print(e)

返回的是空网页

if html is None:
    print('没有找到网页')

目标标签在网页中缺失

try:
    #不存在的标签
    content = bsObj.nonExistingTag.anotherTag 
  except AttributeError as e:
    print('没有找到你想要的标签')
  else:
    if content == None:
      print('没有找到你想要的标签')
    else:
      print(content)

实例

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.h1
  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)

以上全部为本篇文章的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】

Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】

本文实例讲述了Python3实现爬虫爬取赶集网列表功能。分享给大家供大家参考,具体如下: python3爬虫之爬取赶集网列表。这几天一直在学习使用python3爬取数据,今天记录一下,代...

python按综合、销量排序抓取100页的淘宝商品列表信息

进入淘宝网,分别按综合、销量排序抓取100页的所有商品的列表信息。 1、按综合 import re from selenium import webdriver from s...

Python简单实现网页内容抓取功能示例

本文实例讲述了Python简单实现网页内容抓取功能。分享给大家供大家参考,具体如下: 使用模块: import urllib2 import urllib 普通抓取实例:...

Python爬虫工程师面试问题总结

注:答案一般在网上都能够找到。 1.对if __name__ == 'main'的理解陈述 2.python是如何进行内存管理的? 3.请写出一段Python代码实现删除一个lis...

Python常用的爬虫技巧总结

用python也差不多一年多了,python应用最多的场景还是web快速开发、爬虫、自动化运维:写过简单网站、写过自动发帖脚本、写过收发邮件脚本、写过简单验证码识别脚本。 爬虫在开发过程...