Python爬蟲BeautifulSoup4系列之十

1,概述

和 lxml 一樣,Beautiful Soup 也是一個HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 數據。

lxml 只會局部遍歷,而Beautiful Soup 是基於HTML DOM的,會載入整個文檔,解析整個DOM樹,因此時間和內存開銷都會大很多,所以性能要低於lxml。

BeautifulSoup 用來解析 HTML 比較簡單,API非常人性化,支持CSS選擇器、Python標準庫中的HTML解析器,也支持 lxml 的 XML解析器。

Beautiful Soup 3 目前已經停止開發,推薦現在的項目使用Beautiful Soup 4。使用 pip 安裝即可:pip install beautifulsoup4

這裏寫圖片描述

2,四大對象種類

Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每個節點都是Python對象,所有對象可以歸納爲4種:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

1,Tag

Tag 通俗點講就是 HTML 中的一個個標籤以及標籤中的內容


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 對象
soup = BeautifulSoup(html)

print type(soup.p)
# <class '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'] # soup.p.get('class')
# ['title'] #還可以利用get方法,傳入屬性的名稱,二者是等價的

soup.p['class'] = "newClass"
print soup.p # 可以對這些屬性和內容等等進行修改
# <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>

del soup.p['class'] # 還可以對這個屬性進行刪除
print soup.p
# <p name="dromouse"><b>The Dormouse's story</b></p>

2,2. NavigableString

既然我們已經得到了標籤的內容,那麼問題來了,我們要想獲取標籤內部的文字怎麼辦呢?很簡單,用 .string 即可,例如

print soup.p.string
# The Dormouse's story

print type(soup.p.string)
# In [13]: <class 'bs4.element.NavigableString'>

3, BeautifulSoup

BeautifulSoup 對象表示的是一個文檔的內容。大部分時候,可以把它當作 Tag 對象,是一個特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性

print type(soup.name)
# <type 'unicode'>

print soup.name 
# [document]

print soup.attrs # 文檔本身的屬性爲空
# {}

4,Comment

Comment 對象是一個特殊類型的 NavigableString 對象,其輸出的內容不包括註釋符號。

print soup.a
# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>

print soup.a.string
# Elsie 

print type(soup.a.string)
# <class 'bs4.element.Comment'>

a 標籤裏的內容實際上是註釋,但是如果我們利用 .string 來輸出它的內容時,註釋符號已經去掉了。

3,遍歷文檔樹

1. 直接子節點 :.contents .children 屬性

  • tag 的 .content 屬性可以將tag的子節點以列表的方式輸出。輸出方式爲列表,我們可以用列表索引來獲取它的某一個元素

  • .children,它返回的不是一個 list,而是一個list生成器對象,不過我們可以通過遍歷獲取所有子節點。

2,所有子孫節點: .descendants 屬性

.contents 和 .children 屬性僅包含tag的直接子節點,.descendants 屬性可以對所有tag的子孫節點進行遞歸循環,和 children類似,我們也需要遍歷獲取其中的內容。

3,節點內容: .string 屬性

如果tag只有一個 NavigableString 類型子節點,那麼這個tag可以使用 .string 得到子節點。如果一個tag僅有一個子節點,那麼這個tag也可以使用 .string 方法,輸出結果與當前唯一子節點的 .string 結果相同。

通俗點說就是:如果一個標籤裏面沒有標籤了,那麼 .string 就會返回標籤裏面的內容。如果標籤裏面只有唯一的一個標籤了,那麼 .string 也會返回最裏面的內容

4,搜索文檔樹

1,1.find_all(name, attrs, recursive, text, **kwargs)

1)name 參數

name 參數可以查找所有名字爲 name 的tag,字符串對象會被自動忽略掉

A.傳字符串
最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容,

B.傳正則表達式
如果傳入正則表達式作爲參數,Beautiful Soup會通過正則表達式的 match() 來匹配內容.

C.傳列表
如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回.

2)keyword 參數

soup.find_all(id='link2')

3)text 參數

通過 text 參數可以搜搜文檔中的字符串內容,與 name 參數的可選值一樣, text 參數接受 字符串 , 正則表達式 , 列表

2,CSS選擇器

這就是另一種與 find_all 方法有異曲同工之妙的查找方法.

  • 寫 CSS 時,標籤名不加任何修飾,類名前加.,id名前加#

  • 在這裏我們也可以利用類似的方法來篩選元素,用到的方法是 soup.select(),返回類型是 list

(1)通過標籤名查找

print soup.select('title') 
#[<title>The Dormouse's story</title>]

(2)通過類名查找

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>]

(3)通過 id 名查找

print soup.select('#link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(4)組合查找

組合查找即和寫 class 文件時,標籤名與類名、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>]

(5)屬性查找

查找時還可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標籤屬於同一節點,所以中間不能加空格,否則會無法匹配到。

print soup.select('a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

同樣,屬性仍然可以與上述查找方式組合,不在同一節點的空格隔開,同一節點的不加空格

print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(6) 獲取內容

以上的 select 方法返回的結果都是列表形式,可以遍歷形式輸出,然後用 get_text() 方法來獲取它的內容。

soup = BeautifulSoup(html, 'lxml')
print type(soup.select('title'))
print soup.select('title')[0].get_text()

for title in soup.select('title'):
    print title.get_text()

5,使用BeautifulSoup4爬取騰訊社招信息案例

import requests
from bs4 import BeautifulSoup
import json


def tencent(url, item_list):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"}

    # 使用requests模塊的get方法,發送請求,獲取響應的數據
    html = requests.get(url, headers=headers).content
    print("[LOG]: 正在抓取...%s" % url[-3:])
    # 指定lxml解析器,提取html文件
    soup = BeautifulSoup(html, "lxml")

    # select選取html文件中所有的even和odd類,返回的是一個列表
    # 原網頁對於奇數even和偶數odd條目,用不同的顏色區分
    node_list = soup.select(".even, .odd")

    # 循環遍歷每頁的招聘信息
    for node in node_list:
        # 每一個職位要想抓取的信息
        item = {}
        # 職位名
        item["positionName"] = node.select("td a")[0].get_text()
        # 職位鏈接
        item["positionLink"] = "http://hr.tencent.com/" + node.select("td a")[0].get("href")
        # 職位類別
        item["positionType"] = node.select("td")[1].get_text()
        # 職位招聘人數
        item["peopleNumber"] = node.select("td")[2].get_text()
        # 工作地點
        item["workLocation"] = node.select("td")[3].get_text()
        # 發佈時間
        item["publishtimes"] = node_list[0].select("td")[4].get_text()

        item_list.append(item)


if __name__ == "__main__":
    # 騰通社招網站
    url = "http://hr.tencent.com/position.php?&start="
    # 用於裝所有的招聘職位,每頁顯示10條招聘信息
    item_list = []
    # 分析騰訊utl地址,可知
    # start=0  第一頁
    # start=10 第二頁
    # start=20 第三頁
    for page in range(0, 100, 10):
        tencent(url + str(page), item_list)

  # 默認按ascii處理所有文本
  # ensure_ascii = False 表示處理中文時,禁用ascii編碼,按Unicode處理
    content = json.dumps(item_list, ensure_ascii=False)
    with open("tencent.json", "w") as f:
        f.write(content)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章