爬蟲進階--BeautifulSoup的使用(自用)

Beautiful Soup 的用法

上一節咱們介紹了正則表達式,它的內容其實仍是蠻多的,若是一個正則匹配稍有差池,那可能程序就處在永久的循環之中,並且有的小夥伴們也對寫正則表達式的寫法用得不熟練,不要緊,咱們還有一個更強大的工具,叫 Beautiful Soup,有了它咱們能夠很方便地提取出 HTML 或 XML標籤中的內容,實在是方便,這一節就讓咱們一塊兒來感覺一下 Beautiful Soup 的強大吧。html

Beautiful Soup 的簡介

簡單來講,Beautiful Soup 是 python 的一個庫,最主要的功能是從網頁抓取數據。官方解釋以下:python

Beautiful Soup 提供一些簡單的、python 式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,經過解析文檔爲用戶提供須要抓取的數據,由於簡單,因此不須要多少代碼就能夠寫出一個完整的應用程序。
Beautiful Soup 自動將輸入文檔轉換爲 Unicode 編碼,輸出文檔轉換爲 utf-8 編碼。你不須要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup 就不能自動識別編碼方式了。而後,你僅僅須要說明一下原始編碼方式就能夠了。
Beautiful Soup 已成爲和 lxml、html6lib 同樣出色的 python 解釋器,爲用戶靈活地提供不一樣的解析策略或強勁的速度。正則表達式

廢話很少說,咱們來試一下吧~express

Beautiful Soup 安裝

Beautiful Soup 3 目前已經中止開發,推薦在如今的項目中使用 Beautiful Soup 4,不過它已經被移植到 BS4 了,也就是說導入時咱們須要 import bs4 。因此這裏咱們用的版本是 Beautiful Soup 4.3.2 (簡稱BS4),另外聽說 BS4 對 Python3 的支持不夠好,不過我用的是 Python2.7.7,若是有小夥伴用的是 Python3 版本,能夠考慮下載 BS3 版本。markdown

若是你用的是新版的 Debain 或 Ubuntu,那麼能夠經過系統的軟件包管理來安裝,不過它不是最新版本,目前是4.2.1版本函數

sudo apt-get install Python-bs4

若是想安裝最新的版本,請直接下載安裝包來手動安裝,也是十分方便的方法。在這裏我安裝的是 Beautiful Soup 4.3.2工具

Beautiful Soup 3.2.1
Beautiful Soup 4.3.2編碼

下載完成以後解壓翻譯

運行下面的命令便可完成安裝code

sudo python setup.py install

以下圖所示,證實安裝成功了

而後須要安裝 lxml

sudo apt-get install Python-lxml

Beautiful Soup 支持 Python 標準庫中的 HTML 解析器,還支持一些第三方的解析器,若是咱們不安裝它,則 Python 會使用 Python 默認的解析器,lxml 解析器更增強大,速度更快,推薦安裝。

開啓 Beautiful Soup 之旅

在這裏先分享官方文檔連接,不過內容是有些多,也不夠條理,在此本文章作一下整理方便你們參考。

官方文檔

建立 Beautiful Soup 對象

首先必需要導入 bs4 庫

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

建立 beautifulsoup 對象

soup = BeautifulSoup(html)

另外,咱們還能夠用本地 HTML 文件來建立對象,例如

soup = BeautifulSoup(open('index.html'))

上面這句代碼即是將本地 index.html 文件打開,用它來建立 soup 對象

下面咱們來打印一下 soup 對象的內容,格式化輸出

print soup.prettify()
<html>
 <head>
  <title>
   The Dormouse's story
  </title>

以上即是輸出結果,格式化打印出了它的內容,這個函數常常用到,小夥伴們要記好咯。

四大對象種類

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

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

下面咱們進行一一介紹

Tag

Tag 是什麼?通俗點講就是 HTML 中的一個個標籤,例如

<title>The Dormouse's story</title>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

上面的 title a 等等 HTML 標籤加上裏面包括的內容就是 Tag,下面咱們來感覺一下怎樣用 Beautiful Soup 來方便地獲取 Tags

下面每一段代碼中註釋部分即爲運行結果

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 soup.p
\#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

咱們能夠利用 soup 加標籤名輕鬆地獲取這些標籤的內容,是否是感受比正則表達式方便多了?不過有一點是,它查找的是在全部內容中的第一個符合要求的標籤,若是要查詢全部的標籤,咱們在後面進行介紹。

咱們能夠驗證一下這些對象的類型

print type(soup.a)
\#<class 'bs4.element.Tag'>

對於 Tag,它有兩個重要的屬性,是 name 和 attrs,下面咱們分別來感覺一下

name

print soup.name
print soup.head.name
\#[document]
\#head

soup 對象自己比較特殊,它的 name 即爲 [document],對於其餘內部標籤,輸出的值便爲標籤自己的名稱。

attrs

print soup.p.attrs
\#{'class': ['title'], 'name': 'dromouse'}

在這裏,咱們把 p 標籤的全部屬性打印輸出了出來,獲得的類型是一個字典。

若是咱們想要單獨獲取某個屬性,能夠這樣,例如咱們獲取它的 class 叫什麼

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>

還能夠對這個屬性進行刪除,例如

del soup.p['class']
print soup.p
\#<p name="dromouse"><b>The Dormouse's story</b></p>

不過,對於修改刪除的操做,不是咱們的主要用途,在此不作詳細介紹了,若是有須要,請查看前面提供的官方文檔

NavigableString

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

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

這樣咱們就輕鬆獲取到了標籤裏面的內容,想一想若是用正則表達式要多麻煩。它的類型是一個 NavigableString,翻譯過來叫 能夠遍歷的字符串,不過咱們最好仍是稱它英文名字吧。

來檢查一下它的類型

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

BeautifulSoup

BeautifulSoup 對象表示的是一個文檔的所有內容.大部分時候,能夠把它看成 Tag 對象,是一個特殊的 Tag,咱們能夠分別獲取它的類型,名稱,以及屬性來感覺一下

print type(soup.name)
\#<type 'unicode'>
print soup.name 
\# [document]
print soup.attrs 
\#{} 空字典

Comment

Comment 對象是一個特殊類型的 NavigableString 對象,其實輸出的內容仍然不包括註釋符號,可是若是很差好處理它,可能會對咱們的文本處理形成意想不到的麻煩。

咱們找一個帶註釋的標籤

print soup.a
print soup.a.string
print type(soup.a.string)

運行結果以下

<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
 Elsie 
<class 'bs4.element.Comment'>

a 標籤裏的內容其實是註釋,可是若是咱們利用 .string 來輸出它的內容,咱們發現它已經把註釋符號去掉了,因此這可能會給咱們帶來沒必要要的麻煩。

另外咱們打印輸出下它的類型,發現它是一個 Comment 類型,因此,咱們在使用前最好作一下判斷,判斷代碼以下

if type(soup.a.string)==bs4.element.Comment:
    print soup.a.string

上面的代碼中,咱們首先判斷了它的類型,是否爲 Comment 類型,而後再進行其餘操做,如打印輸出。

遍歷文檔樹

直接子節點

要點:.contents .children 屬性

.contents

tag 的 .content 屬性能夠將tag的子節點以列表的方式輸出

print soup.head.contents 
\#[<title>The Dormouse's story</title>]

輸出方式爲列表,咱們能夠用列表索引來獲取它的某一個元素

print soup.head.contents[0]
\#<title>The Dormouse's story</title>

.children

它返回的不是一個 list,不過咱們能夠經過遍歷獲取全部子節點。

咱們打印輸出 .children 看一下,能夠發現它是一個 list 生成器對象

print soup.head.children
\#<listiterator object at 0x7f71457f5710>

咱們怎樣得到裏面的內容呢?很簡單,遍歷一下就行了,代碼及結果以下

for child in  soup.body.children:
    print child
<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 class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and

全部子孫節點

知識點:.descendants 屬性

.descendants

.contents 和 .children 屬性僅包含tag的直接子節點,.descendants 屬性能夠對全部tag的子孫節點進行遞歸循環,和 children相似,咱們也須要遍歷獲取其中的內容。

for child in soup.descendants:
    print child

運行結果以下,能夠發現,全部的節點都被打印出來了,先生最外層的 HTML 標籤,其次從 head 標籤一個個剝離,以此類推。

<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 class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,

節點內容

知識點:.string 屬性

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

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

print soup.head.string
\#The Dormouse's story
print soup.title.string
\#The Dormouse's story

若是 tag 包含了多個子節點,tag 就沒法肯定,string 方法應該調用哪一個子節點的內容, .string 的輸出結果是 None

print soup.html.string
\# None

多個內容

知識點: .strings .stripped_strings 屬性

.strings

獲取多個內容,不過須要遍歷獲取,好比下面的例子

for string in soup.strings:
    print(repr(string))
    \# u"The Dormouse's story"
    \# u'\n\n'
    \# u"The Dormouse's story"
    \# u'\n\n'
    \# u'Once upon a time there were three little sisters; and their names were\n'
    \# u'Elsie'
    \# u',\n'
    \# u'Lacie'
    \# u' and\n'
    \# u'Tillie'
    \# u';\nand they lived at the bottom of a well.'
    \# u'\n\n'
    \# u'...'
    \# u'\n'
.stripped_strings

輸出的字符串中可能包含了不少空格或空行,使用 .stripped_strings 能夠去除多餘空白內容

for string in soup.stripped_strings:
    print(repr(string))
    \# u"The Dormouse's story"
    \# u"The Dormouse's story"
    \# u'Once upon a time there were three little sisters; and their names were'
    \# u'Elsie'
    \# u','
    \# u'Lacie'
    \# u'and'
    \# u'Tillie'
    \# u';\nand they lived at the bottom of a well.'
    \# u'...'

父節點

知識點: .parent 屬性

p = soup.p
print p.parent.name
\#body
content = soup.head.title.string
print content.parent.name
\#title

所有父節點

知識點:.parents 屬性

經過元素的 .parents 屬性能夠遞歸獲得元素的全部父輩節點,例如

content = soup.head.title.string
for parent in  content.parents:
    print parent.name
title
head
html
[document]

兄弟節點

知識點:.next_sibling .previous_sibling 屬性

兄弟節點能夠理解爲和本節點處在統一級的節點,.next_sibling 屬性獲取了該節點的下一個兄弟節點,.previous_sibling 則與之相反,若是節點不存在,則返回 None

注意:實際文檔中的tag的 .next_sibling 和 .previous_sibling 屬性一般是字符串或空白,由於空白或者換行也能夠被視做一個節點,因此獲得的結果多是空白或者換行

print soup.p.next_sibling
\#       實際該處爲空白
print soup.p.prev_sibling
\#None   沒有前一個兄弟節點,返回 None
print soup.p.next_sibling.next_sibling
\#<p class="story">Once upon a time there were three little sisters; and their names were
\#<a class="sister" 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>
\#下一個節點的下一個兄弟節點是咱們能夠看到的節點

所有兄弟節點

知識點:.next_siblings .previous_siblings 屬性

經過 .next_siblings 和 .previous_siblings 屬性能夠對當前節點的兄弟節點迭代輸出

for sibling in soup.a.next_siblings:
    print(repr(sibling))
    \# u',\n'
    \# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
    \# u' and\n'
    \# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
    \# u'; and they lived at the bottom of a well.'
    \# None

先後節點

知識點:.next_element .previous_element 屬性

與 .next_sibling .previous_sibling 不一樣,它並非針對於兄弟節點,而是在全部節點,不分層次

好比 head 節點爲

<head><title>The Dormouse's story</title></head>

那麼它的下一個節點即是 title,它是不分層次關係的

print soup.head.next_element
\#<title>The Dormouse's story</title>

全部先後節點

知識點:.next_elements .previous_elements 屬性

經過 .next_elements 和 .previous_elements 的迭代器就能夠向前或向後訪問文檔的解析內容,就好像文檔正在被解析同樣

for element in last_a_tag.next_elements:
    print(repr(element))
\# u'Tillie'
\# u';\nand they lived at the bottom of a well.'
\# u'\n\n'
\# <p class="story">...</p>
\# u'...'
\# u'\n'
\# None

搜索文檔樹

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

find_all() 方法搜索當前tag的全部tag子節點,並判斷是否符合過濾器的條件

name 參數

name 參數能夠查找全部名字爲 name 的 tag,字符串對象會被自動忽略掉

傳字符串

最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數,Beautiful Soup 會查找與字符串完整匹配的內容,下面的例子用於查找文檔中全部的 標籤

soup.find_all('b')
\# [<b>The Dormouse's story</b>]
print soup.find_all('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>]
傳正則表達式

若是傳入正則表達式做爲參數,Beautiful Soup 會經過正則表達式的 match() 來匹配內容.下面例子中找出全部以b開頭的標籤,這表示 和 標籤都應該被找到

import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
\# body
\# b
傳列表

若是傳入列表參數,Beautiful Soup 會將與列表中任一元素匹配的內容返回.下面代碼找到文檔中全部 <a> 標籤和 <b> 標籤

soup.find_all(["a", "b"])
\# [<b>The Dormouse's story</b>,
\#  <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>]
傳 True

True 能夠匹配任何值,下面代碼查找到全部的 tag,可是不會返回字符串節點

for tag in soup.find_all(True):
    print(tag.name)
\# html
\# head
\# title
\# body
\# p
\# b
\# p
\# a
\# a
傳方法

若是沒有合適過濾器,那麼還能夠定義一個方法,方法只接受一個元素參數 [4] ,若是這個方法返回 True 表示當前元素匹配而且被找到,若是不是則反回 False

下面方法校驗了當前元素,若是包含 class 屬性卻不包含 id 屬性,那麼將返回 True:

def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

將這個方法做爲參數傳入 find_all() 方法,將獲得全部

標籤:

soup.find_all(has_class_but_no_id)
\# [<p class="title"><b>The Dormouse's story</b></p>,
\#  <p class="story">Once upon a time there were...</p>,
\#  <p class="story">...</p>]

keyword 參數

注意:若是一個指定名字的參數不是搜索內置的參數名,搜索時會把該參數看成指定名字 tag 的屬性來搜索,若是包含一個名字爲 id 的參數,Beautiful Soup 會搜索每一個 tag 的 」id」 屬性

soup.find_all(id='link2')
\# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

若是傳入 href 參數,Beautiful Soup 會搜索每一個 tag 的 」href」 屬性

soup.find_all(href=re.compile("elsie"))
\# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

使用多個指定名字的參數能夠同時過濾 tag 的多個屬性

soup.find_all(href=re.compile("elsie"), id='link1')
\# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

在這裏咱們想用 class 過濾,不過 class 是 python 的關鍵詞,這怎麼辦?加個下劃線就能夠

soup.find_all("a", class_="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>]

有些 tag 屬性在搜索不能使用,好比 HTML5 中的 data-* 屬性

data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
data_soup.find_all(data-foo="value")
\# SyntaxError: keyword can't be an expression

可是能夠經過 find_all() 方法的 attrs 參數定義一個字典參數來搜索包含特殊屬性的tag

data_soup.find_all(attrs={"data-foo": "value"})
\# [<div data-foo="value">foo!</div>]

text 參數

經過 text 參數能夠搜搜文檔中的字符串內容.與 name 參數的可選值同樣, text 參數接受 字符串 , 正則表達式 , 列表, True

soup.find_all(text="Elsie")
\# [u'Elsie']

soup.find_all(text=["Tillie", "Elsie", "Lacie"])
\# [u'Elsie', u'Lacie', u'Tillie']

soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]

limit 參數

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

文檔樹中有3個 tag 符合搜索條件,但結果只返回了2個,由於咱們限制了返回數量

soup.find_all("a", limit=2)
\# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
\#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

recursive 參數

調用 tag 的 find_all() 方法時,Beautiful Soup 會檢索當前 tag 的全部子孫節點,若是隻想搜索 tag 的直接子節點,可使用參數 recursive=False .

一段簡單的文檔:

<html\>  
 <head\>  
  <title\>  
   The Dormouse's story  
  </title\>  
 </head\>  
...

是否使用 recursive 參數的搜索結果:

soup.html.find_all("title")
\# [<title>The Dormouse's story</title>]

soup.html.find_all("title", recursive=False)
\# []

find( name , attrs , recursive , text , **kwargs )

它與 find_all() 方法惟一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果

find_parents() fin_parent()

find_all() 和 find() 只搜索當前節點的全部子節點,孫子節點等. find_parents() 和 find_parent() 用來搜索當前節點的父輩節點,搜索方法與普通 tag 的搜索方法相同,搜索文檔搜索文檔包含的內容

find_next_siblings() find_next_sibling()

這2個方法經過 .next_siblings 屬性對當 tag 的全部後面解析的兄弟 tag 節點進行迭代, find_next_siblings() 方法返回全部符合條件的後面的兄弟節點,find_next_sibling() 只返回符合條件的後面的第一個 tag 節點

find_previous_siblings() find_previous_sibling()

這2個方法經過 .previous_siblings 屬性對當前 tag 的前面解析的兄弟 tag 節點進行迭代, find_previous_siblings() 方法返回全部符合條件的前面的兄弟節點, find_previous_sibling() 方法返回第一個符合條件的前面的兄弟節點

find_all_next() find_next()

這2個方法經過 .next_elements 屬性對當前 tag 的以後的 tag 和字符串進行迭代, find_all_next() 方法返回全部符合條件的節點, find_next() 方法返回第一個符合條件的節點

find_all_previous() 和 find_previous()

這2個方法經過 .previous_elements 屬性對當前節點前面的 tag 和字符串進行迭代, find_all_previous() 方法返回全部符合條件的節點, find_previous()方法返回第一個符合條件的節點

注:以上(2)(3)(4)(5)(6)(7)方法參數用法與 find_all() 徹底相同,原理均相似,在此再也不贅述。

CSS選擇器

咱們在寫 CSS 時,標籤名不加任何修飾,類名前加點,id名前加 #,在這裏咱們也能夠利用相似的方法來篩選元素,用到的方法是 soup.select(),返回類型是 list

經過標籤名查找

print soup.select('title') 
\#[<title>The Dormouse's story</title>]
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>]
print soup.select('b')
\#[<b>The Dormouse's story</b>]

經過類名查找

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

經過 id 名查找

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

組合查找

組合查找即和寫 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>]

屬性查找

查找時還能夠加入屬性元素,屬性須要用中括號括起來,注意屬性和標籤屬於同一節點,因此中間不能加空格,不然會沒法匹配到。

print soup.select('a[class="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>]
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>]

--轉載自極客學院《Beautiful Soup 的用法》

相關文章
相關標籤/搜索