爬蟲解析bs4

一. 介紹#

Beautiful Soup 是一個能夠從HTML或XML文件中提取數據的Python庫.它可以經過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工做時間.你可能在尋找 Beautiful Soup3 的文檔,Beautiful Soup 3 目前已經中止開發,官網推薦在如今的項目中使用Beautiful Soup 4, 移植到BS4css

Copy
# 安裝 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解析方法不夠穩定.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"])``BeautifulSoup(markup, "xml") 速度快惟一支持XML的解析器 須要安裝C語言庫
html5lib BeautifulSoup(markup, "html5lib") 最好的容錯性以瀏覽器的方式解析文檔生成HTML5格式的文檔 速度慢不依賴外部擴展

中文文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.htmlhtml5

二. 基本使用#

Copy
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title">zhangchengDSB <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 item" 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

# BeautifulSoup(markup=html_doc, features='html.parser')
soup = BeautifulSoup(markup=html_doc, features='lxml')

# 處理好縮進,結構化顯示
res = soup.prettify()  # /ˈprɪtɪfaɪ/
print(res)
''' <html> <head> <title> The Dormouse's story </title> </head> <body> <p class="title"> zhangchengDSB <b> The Dormouse's story </b> </p> <p class="story"> Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1"> Elsie </a> , <a class="sister" href="http://example.com/lacie" id="link2"> Lacie </a> and <a class="sister" href="http://example.com/tillie" id="link3"> Tillie </a> ; and they lived at the bottom of a well. </p> <p class="story"> ... </p> </body> </html> '''

三. 遍歷文檔樹#

1. 介紹#

Copy
# 優點: 直接經過標籤名字選擇,特色是選擇速度快
# 缺點: 若是存在多個相同的標籤則只返回第一個

# 一、用法
# 二、獲取標籤的名稱
# 三、獲取標籤的屬性
# 四、獲取標籤的內容
# 五、嵌套選擇
# 六、子節點、子孫節點
# 七、父節點、祖先節點
# 八、兄弟節點

2. 用法#

Copy
head = soup.head
print(head)  # <head><title>The Dormouse's story</title></head>

3. 獲取標籤的名稱#

Copy
head = soup.head
print(head.name, type(head.name))  # head <class 'str'>

4. 獲取標籤的屬性#

Copy
p = soup.body.p
print(p.attrs)  # {'class': ['title']}

# 注意: class可能有多個
# <a href="http://example.com/elsie" class="sister item" id="link1">Elsie</a>
a = soup.body.a
print(a.attrs)  # {'href': 'http://example.com/elsie', 'class': ['sister', 'item'], 'id': 'link1'}

5. 獲取標籤的內容#

Copy
# <head><title>The Dormouse's story</title></head>
# <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>
# <a href="http://example.com/elsie" class="sister item" id="link1">Elsie</a>
head = soup.head
p = soup.body.p
a = soup.body.a

# .text: 獲取標籤下全部的文本內容
print(p.text)   # zhangchengDSB The Dormouse's story

# .string: 獲取標籤下只有一個文本內容存在的文本內容
print(p.string)     # None
print(a.string)     # Elsie
print(head.string)  # The Dormouse's story

# .strings: 獲取標籤下全部文本內容, 製做成一個迭代器對象
print(p.strings)        # <generator object _all_strings at 0x0000018C5FC5B4C0>
print(list(p.strings))  # ['zhangchengDSB ', "The Dormouse's story"]

6. 嵌套選擇#

Copy
# <a href="http://example.com/elsie" class="sister item" id="link1">Elsie</a>
a = soup.body.a
print(a)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>
print(a.get('id'))     # link1
print(a.get('class'))  # ['sister', 'item']

7. 子節點、子孫節點#

Copy
# .contents: 獲取標籤下全部子節點 (注意: 包含空格等符號)
res = soup.body.p.contents
print(res)  # ['zhangchengDSB ', <b>The Dormouse's story</b>]

# .children: 獲取標籤下全部全部子節點, 製做成迭代器
res = soup.body.p.children
print(res)         # <list_iterator object at 0x00000205E078AE80>
print(list(res))   # ['zhangchengDSB ', <b>The Dormouse's story</b>]

8. 父節點、祖先節點#

Copy
# .parent: 獲取標籤的父節點(單個)
res = soup.body.p.b.parent
print(res)  # <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>

# .parents: 獲取標籤的全部祖先節點
res = soup.a.parents
print(res)  # <generator object parents at 0x000001E206F4A4C0>
print(len(list(res)))  # 4 (提示: 這是一個迭代器, list取完了就空了)

res = soup.a.parents
print(list(res))
''' [<p class="story">Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p>, <body> <p class="title">zhangchengDSB <b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> </body>, <html><head><title>The Dormouse's story</title></head> <body> <p class="title">zhangchengDSB <b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> </body></html>, <html><head><title>The Dormouse's story</title></head> <body> <p class="title">zhangchengDSB <b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> </body></html>] '''

9. 兄弟節點#

Copy
# .next_sibling: 獲取標籤的下一個兄弟 (提示: 逗號也被涵蓋了, 很差用)
print(soup.a.next_sibling)
''' <p class="title">zhangchengDSB <b>The Dormouse's story</b></p> , '''

# .previous_sibling: 獲取標籤的上一個兄弟 (提示: 空格也被涵蓋了, 也很差用)
print(soup.a.previous_sibling)
''' Once upon a time there were three little sisters; and their names were '''

10. 總結#

Copy
# 注意: 多個標籤結果之返回一條
soup.head             獲取標籤(多條中的第一條) 

soup.head.name        獲取標籤名稱 

soup.head.attrs       獲取標籤屬性 {'class': [xx, yy, ...], 'id': jj}

soup.text             獲取標籤下全部的文本內容
soup.string           獲取標籤下只有一個文本內容存在的文本內容 
soup.strings          獲取標籤下全部文本內容, 製做成一個迭代器對象

soup.get('屬性名')     獲取標籤中的屬性值

soup.contents         獲取標籤下全部子節點 (注意: 包含空格等符號)
soup.children         獲取標籤下全部全部子節點, 製做成迭代器

soup.parent           獲取標籤的父節點(單個)
soup.parents          獲取標籤的全部祖先節點

soup.next_sibling     獲取標籤的下一個兄弟 (提示: 逗號也被涵蓋了, 很差用)
soup.previous_sibling 獲取標籤的上一個兄弟 (提示: 空格也被涵蓋了, 也很差用)

四. 搜索文檔樹#

1. 五種過濾器: 字符串、正則表達式、列表、布爾、方法#

1) 字符串#

Copy
''' .find() 獲取查詢到的第一個 (提示: 內部本質仍是調用了 find_all()[0]) .find_all() 獲取查詢到的全部 '''
# .find()
res = soup.find('a')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>
res = soup.find(name='a')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

res = soup.find(id='link1')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

res = soup.find(class_='sister')
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

res = soup.find(attrs={'class': 'sister'})
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>
res = soup.find(attrs={'id': 'link1'})
print(res)  # <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>

# .find_all()
res = soup.find_all(class_='sister')
print(res)
''' [ <a class="sister item" 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> ] '''

2) 正則表達式#

Copy
import re

pattern = re.compile('^p')
res = soup.find(name=pattern)
print(res)  # <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>

res = soup.find_all(name=pattern)
print(res)
''' [ <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p>, <p class="story">...</p> ] '''

3) 列表#

Copy
res = soup.find_all(name=['b', 'a'])
print(res)
''' [ <b>The Dormouse's story</b>, <a class="sister item" 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> ] '''

4) 布爾#

Copy
res = soup.find_all(id=True)
print(res)
''' [ <a class="sister item" 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> ] '''

res = soup.find_all(href=True)
print(res)
''' [ <a class="sister item" 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> ] '''

5) 方法#

Copy
# 若是沒有合適過濾器,那麼還能夠定義一個方法,方法只接受一個元素參數 ,若是這個方法返回 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))
''' [ <p class="title">zhangchengDSB <b>The Dormouse's story</b></p>, <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p>, <p class="story">...</p> ] '''

6) 總結#

Copy
# 字符串
soup.find('a')     獲取標籤下第一個a標籤
soup.find_all('a') 獲取標籤下全部的a標籤
    
# 正則表達式
import re
pattern = re.compile(r'正則')
soup.find_all(name=pattern)

# 列表
soup.find_all(name=['b', 'a'])

# 布爾
soup.find_all(id=True)
soup.find_all(href=True)

# 方法
soup.find_all(has_class_but_no_id)

2. find_all#

find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)python

Copy
import re

# 1. 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>]

# 3. 按照類名查找,注意關鍵字是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的全部標籤 '''

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

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

# 6. limit參數:若是文檔樹很大那麼搜索會很慢.若是咱們不須要所有結果,可使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字相似,當搜索到的結果數量達到 limit 的限制時,就中止搜索返回結果
print(soup.find_all('a', limit=2))
''' [ <a class="sister item" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> ] '''

# 7. recursive: 調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的全部子孫節點,若是隻想搜索tag的直接子節點,可使用參數 recursive=False .
print(soup.html.find_all('a'))
''' [ <a class="sister item" 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> ] '''
print(soup.html.find_all('a', recursive=False))  # []

總結正則表達式

Copy
# 參數: 
    def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs) """ :param name: 標籤名稱上的過濾器。
        :param attrs: 屬性值的過濾器字典。
        :param recursive: 屬性值的過濾器字典。參數遞歸:若是爲真,find_all()將執行遞歸搜索這個PageElement的子元素。不然,只有直接子女將被考慮。
        :param limit: 若是文檔樹很大那麼搜索會很慢.若是咱們不須要所有結果,可使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字相似,當搜索到的結果數量達到 limit 的限制時,就中止搜索返回結果
        :kwargs: 屬性值的過濾器字典。
        :return: pageelement的結果集。
        """ # 拓展: 等價代碼 soup('a') soup.find('a') soup.p.find_all(text=True) soup.p(text=True) 

3. find#

find(self, name=None, attrs={}, recursive=True, text=None, **kwargs)express

Copy
''' 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>

總結瀏覽器

Copy
soup.find('a') 等價 soup.a 等價 soup.find_all('a')[0]  等價 soup('a')[0]

soup.find('xxxx') 未找到返回None
soup.find_all('xxxx')[0]  和 soup('xxxx')[0]  未找到返回空列表[]

soup.head.a 就是 soup.find(head).find(a)的簡寫

4. 其它方法#

https://www.cummy.com/software/BeautifulSoup/bs4/doc/indx.zh.html#find-parents-find-parentmarkdown

5. CSS選擇器#

Copy
print(soup.p.select('.sister'))
''' [ <a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie</span></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> ] '''
res = soup.select('.sister span')
print(res)  # [<span>Elsie</span>]

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

res = soup.select('#link1 span')
print(res)  # [<span>Elsie</span>]

res = soup.select('#list-2 .element.xxx')
print(res)  # [<li class="element xxx">Bar</li>]

res = soup.select('#list-2')[0].select('.element')
print(res)  # 能夠一直select,但其實不必,一條select就能夠了
''' [<li class="element"><h1 class="yyyy">Foo</h1></li>, <li class="element xxx">Bar</li>, <li class="element">Jay</li>] '''

# 二、獲取屬性
res = soup.select('#list-2 h1')[0].attrs
print(res)  # {'class': ['yyyy']}

# 三、獲取內容
res = soup.select('#list-2 h1')[0].get_text()
print(res)  # Foo

總結app

Copy
# 注意: select返回的結果是多個, 獲取屬性 或者 文本 都須要進行索引取值之後才能操做
soup.p.select('.sister')  
    soup.p(class_='sister') 
    soup.p.find_all(class_='sister')

soup.select('.sister span') 等價 
    li = []
    for sister in soup(class_='sister'):
        if not sister.span:
            continue
        span_list = sister('span')
        for span in span_list:
            li.append(span)
    print(li)
    
soup.select('#link1') 等價 soup(id='link1') 等價 soup.find_all(id='link1')

soup.select('#list-2 h1')[0].attrs 等價 
    soup.find(id='list-2').find_all('h1')[0].attrs 
    soup.find(id='list-2').find('h1').attrs   -> 優化

soup.select('#list-2 h1')[0].get_text() 等價
    soup.find(id='list-2').find('h1').text
    list(soup.find(id='list-2').find('h1').strings)

6. 修改文檔樹#

bs4的修改文檔樹, 軟件配置文件是xml格式的: https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40post

7. 通用性#

拓展性: css選擇器通用, find和find_all用的少. 有些解析器不支持

相關文章
相關標籤/搜索