學習爬蟲第六天 BS4

學習爬蟲第六天 BS4

1. bs4安裝

pip install bs4

2. bs4 簡介

bs4全名: Beautiful Soup
Github地址: 官方連接

3. 基本使用

示例:

from bs4 import BeautifulSoup

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

# 創建Beautiful Soup對象
soup = BeautifulSoup(html_doc, 'html.parser')

print(type(soup))

print(soup)

3-1. 常用方法

方法 說明
.find() 獲取一個對應標籤的值(獲取到首個後便停止)
.find_all() 獲取所有對應標籤的值(後面添加[ 0 ],可獲取對應位置的標籤)

tips:
該方法獲取的值是list,故可以進行切片;
方法示例:

from bs4 import BeautifulSoup

html_doc = """
<table class="tablelist" cellspacing="0" cellpadding="0">
    <tbody>
        <tr class="h">
            <td class="1" width="374">職位名稱</td>
            <td>職位類別</td>
            <td>人數</td>
            <td>地點</td>
            <td>發佈時間</td>
        </tr>
        <tr class="even">
            <td class="l"><a href="https://www.baidu.com">區塊鏈高級研發工程師</a></td>
            <td class="l">技術類</td>
            <td class="l">1</td>
            <td class="l">深圳</td>
            <td class="l">2018-11-25</td>
        </tr>
        <tr class="even">
            <td><a href="https://www.qq.com">金融雲高級後臺開發</a></td>
            <td>技術類</td>
            <td>2</td>
            <td>深圳</td>
            <td>2018-11-24</td>
        </tr>
    </tbody>
</table>
"""

soup = BeautifulSoup(html_doc, 'lxml')

tdf = soup.find('td').parent

#  1.獲取所有tr標籤
trs = soup.find_all('tr')
trs = soup.find('tr')
print(trs)

# 4.將所有id等於test,class也等於test的a標籤提取出來
alist = soup.find_all('a', attrs={"id": "test", "class": "test"})
alist = soup.find_all('a', id="test", class_="test")
print(alist)

# 3.獲取所有的a標籤的href屬性
hrefs = soup.find_all('a')
for a in hrefs:
    print(a)
    # 1.通過下表的方式
    href = a['hrefs']
    如果沒有取到返回None
    href = a.get('hrefs')
    print(href)
    # 2.通過attrs屬性的方式
    href = a.attrs['hrefs']
    print(href)

# 6.獲取所有的職位信息(純文本)
trs = soup.find_all('tr')[1:]
for tr in trs:
    print(tr)
    tds = tr.find_all('td')
    print(tds)
    title = tds[0]
    print(title.string)

    獲取tr標籤的所有文本
    infos = list(tr.strings)
    print(infos)

    可以去除空格取純文本
    infos = list(tr.stripped_strings)
    print(infos[0])

3-2. 解析器

3-2-1. Python標準庫

使用方法: BeautifulSoup(markup, "html.parser")
優勢與劣勢:

優勢 劣勢
1. Python的內置標準庫 2.執⾏速度適中 3.⽂ 檔容錯能⼒強 Python 2.7.3 or 3.2.2)前 的版本中⽂檔 容錯能⼒差

3-2-2. lxml HTML 解析庫

使用方法: BeautifulSoup(markup, "lxml")
優勢與劣勢:

優勢 劣勢
1.速度快 2.⽂檔容錯能 ⼒強 需要安裝C語⾔庫

4. CSS常用選擇器介紹

4-1. 查找常用的方法

通過標籤名查找:

print(soup.select('a'))

通過類名查找:

print(soup.select('.sister')) 查找class=sister的標籤

通過ID查找:

print(soup.select("#link1"))

組合查找: 組合查找即和寫 class ⽂件時,標籤名與類名、id名進⾏的組合原理是⼀樣 的,例如查找 p 標籤中,id 等於 link1的內容,⼆者需要⽤空格分開:

print(soup.select("p #link1"))

直接子標籤查找,則使用 > 分隔:

print(soup.select("head > title"))

通過屬性查找:

print(soup.select('a[href="http://example.com/elsie"]'))

4-2. 獲取內容

get_text()方法 獲取內容
tips:以上的 select ⽅法返回的結果都是列表形式,可以遍歷形式輸出。

4-3. select和css選擇器提取元素

示例html:

html_doc = """
<table class="tablelist" cellspacing="0" cellpadding="0">
    <tbody>
        <tr class="h">
            <td class="1" width="374">職位名稱</td>
            <td>職位類別</td>
            <td>人數</td>
            <td>地點</td>
            <td>發佈時間</td>
        </tr>
        <tr class="even">
            <td class="l"><a href="https://www.baidu.com">區塊鏈高級研發工程師</a></td>
            <td class="l">技術類</td>
            <td class="l">1</td>
            <td class="l">深圳</td>
            <td class="l">2018-11-25</td>
        </tr>
        <tr>
            <td><a href="https://www.qq.com">金融雲高級後臺開發</a></td>
            <td>技術類</td>
            <td>2</td>
            <td>深圳</td>
            <td>2018-11-24</td>
        </tr>
        <tr>
            <td><a href="https://www.zero.com">高級研發工程師</a></td>
            <td>技術類</td>
            <td>2</td>
            <td>深圳</td>
            <td>2018-11-24</td>
        </tr>
        <tr>
            <td><a href="https://www.python.com">高級圖像算法工程師</a></td>
            <td>技術類</td>
            <td>2</td>
            <td>深圳</td>
            <td>2018-11-24</td>
        </tr>
        <tr>
            <td><a href="https://www.llp.com" id="test" class="test">高級業務運維工程師</a></td>
            <td>技術類</td>
            <td>2</td>
            <td>深圳</td>
            <td>2018-11-24</td>
        </tr>
    </tbody>
</table>
"""

使用方法示例:

from bs4 import BeautifulSoup


soup = BeautifulSoup(html_doc, 'lxml')

# 1.獲取所有tr標籤
trs = soup.select('tr')
print(trs)

# 2.獲取第2個tr標籤
tr = soup.select('tr')[1]
print(tr)

# 3.獲取所有class等於even的tr標籤
tr = soup.select('tr.even')
print(tr)

# 4.獲取所有的a標籤的href屬性
alist = soup.select('a')
for a in alist:
    href = a.get('href')
    print(href)

# 5.獲取所有的職位信息(純文本)
trs = soup.select('tr')

for tr in trs:
    infos = list(tr.stripped_strings)
    print(infos)

5. bs4 四大對象

四大對象:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

6. 遍歷文檔樹

  • contents 返回所有子節點的列表
  • children返回所有⼦節點的迭代器
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章