python之BeautifulSoup庫

 1. BeautifulSoup庫簡介

和 lxml 同樣,Beautiful Soup 也是一個HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 數據。lxml 只會局部遍歷,而Beautiful Soup 是基於HTML DOM(Document Object Model)的,會載入整個文檔,解析整個DOM樹,所以時間和內存開銷都會大不少,因此性能要低於lxml。BeautifulSoup 用來解析 HTML 比較簡單,API很是人性化,支持CSS選擇器、Python標準庫中的HTML解析器,也支持 lxml 的 XML解析器。Beautiful Soup 3 目前已經中止開發,推薦如今的項目使用Beautiful Soup 4。css

安裝和文檔:html

1. 安裝html5

#安裝 Beautiful Soup
pip install beautifulsoup4

#安裝解析器
Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml .根據操做系統不一樣,能夠選擇下列方法來安裝lxml:

$ apt-get install Python-lxml

$ easy_install lxml

$ pip install lxml

另外一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同,能夠選擇下列方法來安裝html5lib:

$ apt-get install Python-html5lib

$ easy_install html5lib

$ pip install html5lib

下表列出了主要的解析器,以及它們的優缺點,官網推薦使用lxml做爲解析器,由於效率更高. 在Python2.7.3以前的版本和Python3中3.2.2以前的版本,必須安裝lxml或html5lib, 由於那些Python版本的標準庫中內置的HTML解析方法不夠穩定.正則表達式

解析器 使用方法 優點 劣勢
Python標準庫 BeautifulSoup(markup, "html.parser")
  • Python的內置標準庫
  • 執行速度適中
  • 文檔容錯能力強
  • Python 2.7.3 or 3.2.2)前 的版本中文檔容錯能力差
lxml HTML 解析器 BeautifulSoup(markup, "lxml")
  • 速度快
  • 文檔容錯能力強
  • 須要安裝C語言庫
lxml XML 解析器

BeautifulSoup(markup, ["lxml", "xml"])express

BeautifulSoup(markup, "xml")瀏覽器

  • 速度快
  • 惟一支持XML的解析器
  • 須要安裝C語言庫
html5lib BeautifulSoup(markup, "html5lib")
  • 最好的容錯性
  • 以瀏覽器的方式解析文檔
  • 生成HTML5格式的文檔
  • 速度慢
  • 不依賴外部擴展

2. Beautiful Soup中文文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.htmlapp

3. 幾大解析工具對比:ide

解析工具 解析速度 使用難度
BeautifulSoup 最慢 最簡單
lxml 簡單
正則 最快 最難

2. BeautifulSoup詳解

2.1 BeautifulSoup簡單使用

from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

#建立 Beautiful Soup 對象
# 使用lxml來進行解析
soup = BeautifulSoup(html,"lxml")

print(soup.prettify())

2.2 BeautifulSoup四個經常使用的對象

Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每一個節點都是Python對象,全部對象能夠概括爲4種:工具

  1. Tag
  2. NavigatableString
  3. BeautifulSoup
  4. Comment

 2.2.1. Tag類

Tag 通俗點講就是 HTML 中的一個個標籤。示例代碼以下:post

#-*-coding = utf-8 -*-
from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup  = BeautifulSoup(html,'lxml')
print(soup.title)# <title>The Dormouse's story</title>
print(soup.head)#<head><title>The Dormouse's story</title></head>
print(soup.a)#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print(type(soup.p))#<class 'bs4.element.Tag'>
#咱們能夠利用 soup 加標籤名輕鬆地獲取這些標籤的內容,這些對象的類型是bs4.element.Tag。可是注意,它查找的是在全部內容中的第一個符合要求的標籤。若是要查詢全部的標籤,後面會進行介紹。
#對於Tag,它有兩個重要的屬性,分別是name和attrs。示例代碼以下:
print(soup.name)# [document] #soup 對象自己比較特殊,它的 name 即爲 [document]
print(soup.head.name)#head ,對於其餘內部標籤,輸出的值便爲標籤自己的名稱
print(soup.p.attrs)#{'class': ['title'], 'name': 'dromouse'}返回的是P標籤的屬性字典
print(soup.p['class'])#['title'],返回屬性名對應的屬性值,還能夠利用get方法,傳入屬性的名稱,兩者是等價的
print(soup.p.get('class'))#['title']
soup.p['class'] = 'newclass'#能夠對這些屬性和內容等等進行修改
print(soup.p)#<p class="newclass" name="dromouse"><b>The Dormouse's story</b></p>
Tag

 2.2.2  NavigableString類

 若是拿到標籤後,還想獲取標籤中的內容。那麼能夠經過tag.string獲取標籤中的文字。示例代碼以下:

print(soup.p.string)#The Dormouse's story
print(type(soup.p.string))# <class 'bs4.element.NavigableString'>

 2.2.3 BeautifulSoup類

BeautifulSoup 對象表示的是一個文檔的所有內容。大部分時候,能夠把它看成 Tag 對象,它支持 遍歷文檔樹和搜索文檔 中描述的大部分的方法。由於 BeautifulSoup 對象並非真正的HTML或XML的tag,因此它沒有name和attribute屬性。但有時查看它的 .name 屬性是很方便的,因此 BeautifulSoup 對象包含了一個值爲 「[document]」 的特殊屬性 .name。

soup.name
# '[document]'

 2.2.4 Comment類

Tag , NavigableString , BeautifulSoup 幾乎覆蓋了html和xml中的全部內容,可是還有一些特殊對象:文檔的註釋部分

markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
type(comment)
# <class 'bs4.element.Comment'>

 2.2.5 練習

#遍歷文檔樹:即直接經過標籤名字選擇,特色是選擇速度快,但若是存在多個相同的標籤則只返回第一個
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

#一、用法
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')
# soup=BeautifulSoup(open('a.html'),'lxml')

print(soup.p) #存在多個相同的標籤則只返回第一個
print(soup.a) #存在多個相同的標籤則只返回第一個

#二、獲取標籤的名稱
print(soup.p.name)

#三、獲取標籤的屬性
print(soup.p.attrs)

#四、獲取標籤的內容
print(soup.p.string) # p下的文本只有一個時,取到,不然爲None
print(soup.p.strings) #拿到一個生成器對象, 取到p下全部的文本內容
print(soup.p.text) #取到p下全部的文本內容
for line in soup.stripped_strings: #去掉空白
    print(line)


'''
若是tag包含了多個子節點,tag就沒法肯定 .string 方法應該調用哪一個子節點的內容, .string 的輸出結果是 None,若是隻有一個子節點那麼就輸出該子節點的文本,好比下面的這種結構,soup.p.string 返回爲None,但soup.p.strings就能夠找到全部文本
<p id='list-1'>
    哈哈哈哈
    <a class='sss'>
        <span>
            <h1>aaaa</h1>
        </span>
    </a>
    <b>bbbbb</b>
</p>
'''

#五、嵌套選擇
print(soup.head.title.string)
print(soup.body.a.string)


#六、子節點、子孫節點
print(soup.p.contents) #p下全部子節點
print(soup.p.children) #獲得一個迭代器,包含p下全部子節點

for i,child in enumerate(soup.p.children):
    print(i,child)

print(soup.p.descendants) #獲取子孫節點,p下全部的標籤都會選擇出來
for i,child in enumerate(soup.p.descendants):
    print(i,child)

#七、父節點、祖先節點
print(soup.a.parent) #獲取a標籤的父節點
print(soup.a.parents) #找到a標籤全部的祖先節點,父親的父親,父親的父親的父親...


#八、兄弟節點
print('=====>')
print(soup.a.next_sibling) #下一個兄弟
print(soup.a.previous_sibling) #上一個兄弟

print(list(soup.a.next_siblings)) #下面的兄弟們=>生成器對象
print(soup.a.previous_siblings) #上面的兄弟們=>生成器對象
View Code
#-*-coding = utf-8 -*-
from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
#3.搜索文檔樹
#1)搜索文檔樹,通常用得比較多的就是兩個方法,一個是find,一個是find_all。
# find方法是找到第一個知足條件的標籤後就當即返回,只返回一個元素。
# find_all方法是把全部知足條件的標籤都選到,而後返回。
# 使用這兩個方法,最經常使用的用法是輸入標籤名name以及attr參數找出符合要求的標籤。
soup = BeautifulSoup(html,'lxml')
aList = soup.find_all('a',attrs={'id':'link2'})
print(aList)#[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
#或者是直接傳入屬性的的名字做爲關鍵字參數:
soup.find_all("a",id='link2')
#2)select方法
#使用以上方法能夠方便的找出元素。但有時候使用css選擇器的方式能夠更加的方便。
# 使用css選擇器的語法,應該使用select方法。如下列出幾種經常使用的css選擇器方法:
#a)經過標籤名查找
print(soup.select('a'))#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
#b)經過類名查找
#經過類名,則應該在類的前面加一個.。好比要查找class=sister的標籤。示例代碼以下:
print(soup.select('.sister'))#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
#c)經過id查找
#經過id查找,應該在id的名字前面加一個#號。示例代碼以下:
print(soup.select('#link1'))#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
#d)組合查找
#組合查找和寫 css 文件時,標籤名與類名、id名進行的組合原理是同樣的,例如查找 p 標籤中,id 等於 link1的內容,兩者須要用空格分開:
print(soup.select("p #link1"))#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
#直接子標籤查找,則使用 > 分隔:
print(soup.select('head > title'))#[<title>The Dormouse's story</title>]
#e)經過屬性查找
#查找時還能夠加入屬性元素,屬性須要用中括號括起來,注意屬性和標籤屬於同一節點,因此中間不能加空格,不然會沒法匹配到。示例代碼以下:
print(soup.select('a[href="http://example.com/elsie"]'))#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
#f)在根據類名或者id進行查找的時候,若是還要根據標籤名進行過濾,那麼能夠在類的前面或者id的前面加上標籤名字
print(soup.select('p.title'))#[<p class="title"><b>The Dormouse's story</b></p>]
print(soup.select('a#link1'))#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
#g)獲取內容
#以上的 select 方法返回的結果都是列表形式,能夠遍歷形式輸出,而後用 get_text() 方法來獲取它的內容。
print(soup.select('title'))
print (soup.select('title')[0].get_text())

for title in soup.select('title'):
    print (title.get_text())
css選擇器
#搜索文檔樹:BeautifulSoup定義了不少搜索方法,這裏着重介紹2個: find() 和 find_all() .其它方法的參數和用法相似
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""


from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')

#一、五種過濾器: 字符串、正則表達式、列表、True、方法
#1.一、字符串:即標籤名
print(soup.find_all('b'))

#1.二、正則表達式
import re
print(soup.find_all(re.compile('^b'))) #找出b開頭的標籤,結果有body和b標籤

#1.三、列表:若是傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回.下面代碼找到文檔中全部<a>標籤和<b>標籤:
print(soup.find_all(['a','b']))

#1.四、True:能夠匹配任何值,下面代碼查找到全部的tag,可是不會返回字符串節點
print(soup.find_all(True))
for tag in soup.find_all(True):
    print(tag.name)

#1.五、方法:若是沒有合適過濾器,那麼還能夠定義一個方法,方法只接受一個元素參數 ,若是這個方法返回 True 表示當前元素匹配而且被找到,若是不是則反回 False
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(has_class_but_no_id))


#二、find_all( name , attrs , recursive , text , **kwargs )
#2.一、name: 搜索name參數的值可使任一類型的 過濾器 ,字符竄,正則表達式,列表,方法或是 True .
print(soup.find_all(name=re.compile('^t')))

#2.二、keyword: key=value的形式,value能夠是過濾器:字符串 , 正則表達式 , 列表, True .
print(soup.find_all(id=re.compile('my')))
print(soup.find_all(href=re.compile('lacie'),id=re.compile('\d'))) #注意類要用class_
print(soup.find_all(id=True)) #查找有id屬性的標籤

# 有些tag屬性在搜索不能使用,好比HTML5中的 data-* 屬性:
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
# data_soup.find_all(data-foo="value") #報錯:SyntaxError: keyword can't be an expression
# 可是能夠經過 find_all() 方法的 attrs 參數定義一個字典參數來搜索包含特殊屬性的tag:
print(data_soup.find_all(attrs={"data-foo": "value"}))
# [<div data-foo="value">foo!</div>]

#2.三、按照類名查找,注意關鍵字是class_,class_=value,value能夠是五種選擇器之一
print(soup.find_all('a',class_='sister')) #查找類爲sister的a標籤
print(soup.find_all('a',class_='sister ssss')) #查找類爲sister和sss的a標籤,順序錯誤也匹配不成功
print(soup.find_all(class_=re.compile('^sis'))) #查找類爲sister的全部標籤

#2.四、attrs
print(soup.find_all('p',attrs={'class':'story'}))

#2.五、text: 值能夠是:字符,列表,True,正則
print(soup.find_all(text='Elsie'))
print(soup.find_all('a',text='Elsie'))

#2.六、limit參數:若是文檔樹很大那麼搜索會很慢.若是咱們不須要所有結果,可使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字相似,當搜索到的結果數量達到 limit 的限制時,就中止搜索返回結果
print(soup.find_all('a',limit=2))

#2.七、recursive:調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的全部子孫節點,若是隻想搜索tag的直接子節點,可使用參數 recursive=False .
print(soup.html.find_all('a'))
print(soup.html.find_all('a',recursive=False))

'''
像調用 find_all() 同樣調用tag
find_all() 幾乎是Beautiful Soup中最經常使用的搜索方法,因此咱們定義了它的簡寫方法. BeautifulSoup 對象和 tag 對象能夠被看成一個方法來使用,這個方法的執行結果與調用這個對象的 find_all() 方法相同,下面兩行代碼是等價的:
soup.find_all("a")
soup("a")
這兩行代碼也是等價的:
soup.title.find_all(text=True)
soup.title(text=True)
'''
#三、find( name , attrs , recursive , text , **kwargs )
find_all() 方法將返回文檔中符合條件的全部tag,儘管有時候咱們只想獲得一個結果.好比文檔中只有一個<body>標籤,那麼使用 find_all() 方法來查找<body>標籤就不太合適, 使用 find_all 方法並設置 limit=1 參數不如直接使用 find() 方法.下面兩行代碼是等價的:

soup.find_all('title', limit=1)
# [<title>The Dormouse's story</title>]
soup.find('title')
# <title>The Dormouse's story</title>

惟一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果.
find_all() 方法沒有找到目標是返回空列表, find() 方法找不到目標時,返回 None .
print(soup.find("nosuchtag"))
# None

soup.head.title 是 tag的名字 方法的簡寫.這個簡寫的原理就是屢次調用當前tag的 find() 方法:

soup.head.title
# <title>The Dormouse's story</title>
soup.find("head").find("title")
# <title>The Dormouse's story</title>
find()/find_all()
#-*-coding = utf-8 -*-
from bs4 import BeautifulSoup
import requests
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
url ='http://www.weather.com.cn/textFC/hb.shtml'
def parse_page(url):
    data = []
    response = requests.request(method='get',url =url,headers=headers)
    text = response.content.decode('utf-8')
    soup = BeautifulSoup(text,'html5lib')
    comMidtab = soup.find(name='div',class_ = 'conMidtab')
    tables = comMidtab.find_all('table')
    for table in tables:
        trs = table.find_all('tr')[2:]
        for index,tr in enumerate(trs):
            tds = tr.find_all('td')
            if index == 0:
                city = list(tds[1].stripped_strings)[0]
            else:
                city = list(tds[0].stripped_strings)[0]
            min_temp = list(tds[-2].stripped_strings)[0]
            data.append({'city':city,'min_temp':min_temp})
    return data

def main():
    AllData =[]
    urls = [
        'http://www.weather.com.cn/textFC/hb.shtml',
        'http://www.weather.com.cn/textFC/db.shtml',
        'http://www.weather.com.cn/textFC/hd.shtml',
        'http://www.weather.com.cn/textFC/hz.shtml',
        'http://www.weather.com.cn/textFC/hn.shtml',
        'http://www.weather.com.cn/textFC/xb.shtml',
        'http://www.weather.com.cn/textFC/xn.shtml',
        'http://www.weather.com.cn/textFC/gat.shtml'
    ]
    for url in urls:
        datas = parse_page(url)
        for data in datas:
            AllData.append(data)
    #根據最低氣溫進行排序
    AllData.sort(key=lambda data:data['min_temp'])
    print(AllData)


if __name__=='__main__':
    main()
爬取中國天氣網信息

 

 

 

>>>>待續

相關文章
相關標籤/搜索