python

BeautifulSoup初识

2018-11-13  本文已影响0人  Pope_Li

什么是BeautifulSoup

BeautifulSoup库的名字来源于<爱丽丝梦游仙境>里的同名诗歌它通过定位HTML标签来格式化和组织复杂的网络信息,用简单易用的Python对象为我们展现XML结构信息.

安装BeautifulSoup

安装好python和pip后

Mac系统安装

$sudo easy_install pip
$pip install beautifulsoup4

Linux安装

$sudo apt-get install python-bs4

Win安装

$pip install beautifulsoup4

运行Beautifulsoup

安装好后我们来运行一下,看看beautifulsoup4的强大,我们用https://500px.com来做测试

from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen("https://500px.com")
bsObj = BeautifulSoup(html.read())
print(bsObj.h1)
<h1 class="header_section__headline">Get inspired and share your best photos</h1>

我们已经提取了https://500px.com这个HTML页面里的<h1>标签了,在这之前最好有HTML语言的基础,因为这样可以更精准的提取HTML和XML节点信息.

容错处理

在爬取的过程中经常出现一些错误,造成这些错误的原因可能是网页数据格式不友好,网站服务器宏机,目标数据的标签找不到,这个时候我们就需要做下容错处理.
我们先来分析一下我们经常会遇到的错误

第一种异常程序会返回HTTP错误,HTTP错误可能是"404 Page Not Found""""500 Internal Sever Error"等,这些错误都会抛出一个"HTTPError"异常.

我们用下面方式来处理:

try:
    html = urlopen("https://500px.com")
except HTTPError as e:
    print(e)
    # 返回空值,中断程序或者执行别的程序
else:
    #程序继续

第二种异常发生的时候,uropen会返回一个None对象,所以我们可以增加一个判断语句检测返回的html是不是None

if html is None:
    print('URL is not found')
else:
    #程序继续

如果你要找的标签在Beautifulsoup里没有,找不到就会返回一个AttributeError错误.
例如:

from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen("https://500px.com")
bsObj = BeautifulSoup(html.read())
print(bsObj.nonEX)        # nonEX是一个虚拟标签,在beautifulsoup里边没有
None

这时候返回了一个None,如果不检查,直接调用这个None对象的子标签,就会有错误:

print(bsObj.nonEX.someTag)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-5-f4d08128503b> in <module>()
----> 1 print(bsObj.nonEX.someTag)


AttributeError: 'NoneType' object has no attribute 'someTag'

那么我们怎么避免这两个异常呢?通常的情况下我们可以把两个错误写一起,但是那样会显得累赘,所以我们在网络爬虫的情况下一般写成这样:

from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.request import HTTPError
def getTitle(url):
    try:
        html = ulopen(url)
    except HTTPError as e:
        return None
    try:
        bsObj = BeautifulSoup(html.read())
        title = bsObj.body.h1
    except AttributeError as e :
        return None
    return title
title = getTitle("https://500px.com")
if title == None:
    print('Title could not be found')
else:
    print(title)
上一篇 下一篇

猜你喜欢

热点阅读