溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

BeautifuSoup庫(kù)如何在Python中使用

發(fā)布時(shí)間:2021-01-06 15:59:32 來(lái)源:億速云 閱讀:184 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)BeautifuSoup庫(kù)如何在Python中使用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

BeautifulSoup簡(jiǎn)介

Beautiful Soup是python的一個(gè)庫(kù),最主要的功能是從網(wǎng)頁(yè)抓取數(shù)據(jù)。官方解釋如下:

Beautiful Soup提供一些簡(jiǎn)單的、python式的函數(shù)用來(lái)處理導(dǎo)航、搜索、修改分析樹(shù)等功能。它是一個(gè)工具箱,通過(guò)解析文檔為用戶提供需要抓取的數(shù)據(jù),因?yàn)楹?jiǎn)單,所以不需要多少代碼就可以寫(xiě)出一個(gè)完整的應(yīng)用程序。

Beautiful Soup自動(dòng)將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒(méi)有指定一個(gè)編碼方式,這時(shí),Beautiful Soup就不能自動(dòng)識(shí)別編碼方式了。然后,你僅僅需要說(shuō)明一下原始編碼方式就可以了。

Beautiful Soup已成為和lxml、html6lib一樣出色的python解釋器,為用戶靈活地提供不同的解析策略或強(qiáng)勁的速度。 

BeautifulSoup支持Python標(biāo)準(zhǔn)庫(kù)中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會(huì)使用 Python默認(rèn)的解析器,lxml 解析器更加強(qiáng)大,速度更快,推薦使用lxml 解析器。

1.  創(chuàng)建 BeautifulSoup 對(duì)象

首先導(dǎo)入庫(kù) bs4   lxml  requests

#encoding:UTF-8
from bs4 import BeautifulSoup
import lxml
import requests

使用官方字符串來(lái)演示:

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" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

創(chuàng)建 beautifulsoup 對(duì)象:

soup = BeautifulSoup(html,'lxml') #創(chuàng)建 beautifulsoup 對(duì)象

還可以用本地 HTML 文件來(lái)創(chuàng)建對(duì)象:

soup1 = BeautifulSoup(open('index.html')) #用本地 HTML 文件來(lái)創(chuàng)建對(duì)象

打印一下 soup 對(duì)象的內(nèi)容,格式化輸出:

print soup.prettify() #打印 soup 對(duì)象的內(nèi)容,格式化輸出

輸出結(jié)果,格式化打印出了它的內(nèi)容,這個(gè)函數(shù)經(jīng)常用到。

2.  四種對(duì)象

Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹(shù)形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是Python對(duì)象,所有對(duì)象可以歸納為4種:

  • Tag

  • NavigableString

  • BeautifulSoup

  • Comment

(1)Tag

Tag就是 HTML 中的一個(gè)個(gè)標(biāo)簽,例如:

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

用 BeautifulSoup 可以很方便地獲取 Tags:

print soup.title
print soup.head
print soup.a
print soup.p
print type(soup.a)

這種方式查找的是在所有內(nèi)容中的第一個(gè)符合要求的標(biāo)簽。

對(duì)于 Tag,它有兩個(gè)重要的屬性,name 和 attrs :

print soup.name
print soup.a.name
print soup.attrs
print soup.p.attrs #在這里,我們把 p 標(biāo)簽的所有屬性打印輸出了出來(lái),得到的類型是一個(gè)字典。
print soup.p['class'] #單獨(dú)獲取某個(gè)屬性
print soup.p.get('class') ##單獨(dú)獲取某個(gè)屬性 跟上面一樣的

可以對(duì)這些屬性和內(nèi)容等等進(jìn)行修改:

soup.p['class']="newClass"

也可以對(duì)這個(gè)屬性進(jìn)行刪除:

del soup.p['class']

(2)NavigableString

得到了標(biāo)簽的內(nèi)容用 .string 即可獲取標(biāo)簽內(nèi)部的文字,例如:

print soup.p.string

來(lái)檢查一下它的類型:

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

可以看到它的類型是一個(gè) NavigableString,翻譯過(guò)來(lái)叫 可以遍歷的字符串。

(3)BeautifulSoup

BeautifulSoup 對(duì)象表示的是一個(gè)文檔的全部?jī)?nèi)容.大部分時(shí)候,可以把它當(dāng)作 Tag 對(duì)象,是一個(gè)特殊的 Tag,我們可以分別獲取它的類型,名稱:

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

(4)Comment

Comment 對(duì)象是一個(gè)特殊類型的 NavigableString 對(duì)象,其實(shí)輸出的內(nèi)容仍然不包括注釋符號(hào)。我們找一個(gè)帶注釋的標(biāo)簽:

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

運(yùn)行結(jié)果如下:

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

a 標(biāo)簽里的內(nèi)容實(shí)際上是注釋,但是如果我們利用 .string 來(lái)輸出它的內(nèi)容,我們發(fā)現(xiàn)它已經(jīng)把注釋符號(hào)去掉了,所以這可能會(huì)給我們帶來(lái)不必要的麻煩。

我們打印輸出下它的類型,發(fā)現(xiàn)它是一個(gè) Comment 類型,所以,我們?cè)谑褂们白詈米鲆幌屡袛?,判斷代碼如下:

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

上面的代碼中,我們判斷了它的類型,是否為 Comment 類型。

3.   遍歷文檔樹(shù)

(1)直接子節(jié)點(diǎn)

tag 的 .content 屬性可以將tag的子節(jié)點(diǎn)以列表的方式輸出:

print soup.head.contents 
#運(yùn)行結(jié)果:
#[<title>The Dormouse's story</title>]
 
#輸出方式為列表,我們可以用列表索引來(lái)獲取它的某一個(gè)元素:
print soup.head.contents[0]

.children

它返回的不是一個(gè) list,不過(guò)我們可以通過(guò)遍歷獲取所有子節(jié)點(diǎn)。我們打印輸出 .children 看一下,可以發(fā)現(xiàn)它是一個(gè) list 生成器對(duì)象:

print soup.head.children
#運(yùn)行結(jié)果:
#<listiterator object at 0x7f71457f5710>
 
#遍歷一下獲得里面的內(nèi)容:
for item in soup.body.children:
  print item

(2)所有子孫節(jié)點(diǎn)

.contents 和 .children 屬性僅包含tag的直接子節(jié)點(diǎn),.descendants 屬性可以對(duì)所有tag的子孫節(jié)點(diǎn)進(jìn)行遞歸循環(huán),和 children類似,要獲取其中的內(nèi)容,我們需要對(duì)其進(jìn)行遍歷:

for item in soup.descendants:
  print item
 
#查看運(yùn)行結(jié)果,可以發(fā)現(xiàn),所有的節(jié)點(diǎn)都被打印出來(lái)了:
#<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" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>,

(3)節(jié)點(diǎn)內(nèi)容

如果一個(gè)標(biāo)簽里面沒(méi)有標(biāo)簽了,那么 .string 就會(huì)返回標(biāo)簽里面的內(nèi)容。如果標(biāo)簽里面只有唯一的一個(gè)標(biāo)簽了,那么 .string 也會(huì)返回最里面的內(nèi)容:

print soup.head.string
#運(yùn)行結(jié)果:
#The Dormouse's story
 
#第二種情況:
print soup.title.string
#運(yùn)行結(jié)果:
#The Dormouse's story

如果tag包含了多個(gè)子節(jié)點(diǎn),tag就無(wú)法確定,string 方法應(yīng)該調(diào)用哪個(gè)子節(jié)點(diǎn)的內(nèi)容, .string 的輸出結(jié)果是 None:

print soup.html.string
#運(yùn)行結(jié)果:
#None

(4)多個(gè)內(nèi)容

.strings 獲取多個(gè)內(nèi)容,不過(guò)需要遍歷獲取,比如下面的例子:

for string in soup.strings:
  print(repr(string))

輸出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白內(nèi)容:

for string in soup.stripped_strings:
  print(repr(string))

(5)父節(jié)點(diǎn)

p = soup.p
print p.parent.name
#運(yùn)行結(jié)果:
#body
 
content = soup.head.title.string
print content.parent.name
#運(yùn)行結(jié)果:
#title

(6)全部父節(jié)點(diǎn)

通過(guò)元素的 .parents 屬性可以遞歸得到元素的所有父輩節(jié)點(diǎn):

content = soup.head.title.string
for parent in content.parents:
  print parent.name

(7)兄弟節(jié)點(diǎn)

兄弟節(jié)點(diǎn)可以理解為和本節(jié)點(diǎn)處在統(tǒng)一級(jí)的節(jié)點(diǎn),.next_sibling 屬性獲取了該節(jié)點(diǎn)的下一個(gè)兄弟節(jié)點(diǎn),.previous_sibling 屬性獲取了該節(jié)點(diǎn)的上一個(gè)兄弟節(jié)點(diǎn),如果節(jié)點(diǎn)不存在,則返回 None

注意:實(shí)際文檔中的tag的 .next_sibling 和 .previous_sibling 屬性通常是字符串或空白,因?yàn)榭瞻谆蛘邠Q行也可以被視作一個(gè)節(jié)點(diǎn),所以得到的結(jié)果可能是空白或者換行。

print soup.p.next_sibling
#    實(shí)際該處為空白
print soup.p.prev_sibling
#None  沒(méi)有前一個(gè)兄弟節(jié)點(diǎn),返回 None
print soup.p.next_sibling.next_sibling

(8)全部兄弟節(jié)點(diǎn)

通過(guò) .next_siblings 和 .previous_siblings 屬性可以對(duì)當(dāng)前節(jié)點(diǎn)的兄弟節(jié)點(diǎn)迭代輸出:

for sibling in soup.a.next_siblings:
  print(repr(sibling))

(9)前后節(jié)點(diǎn)

與 .next_sibling  .previous_sibling 不同,它并不是針對(duì)于兄弟節(jié)點(diǎn),而是在所有節(jié)點(diǎn),不分層次

#比如head節(jié)點(diǎn)為:
<head><title>The Dormouse's story</title></head>
#那么它的下一個(gè)節(jié)點(diǎn)便是 title,它是不分層次關(guān)系的。
print soup.head.next_element
#<title>The Dormouse's story</title>

(10)所有前后節(jié)點(diǎn)

通過(guò) .next_elements 和 .previous_elements 的迭代器就可以向前或向后訪問(wèn)文檔的解析內(nèi)容:

for element in last_a_tag.next_elements:
  print(repr(element))

4.  搜索文檔樹(shù)

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

find_all() 方法搜索當(dāng)前tag的所有tag子節(jié)點(diǎn),并判斷是否符合過(guò)濾器的條件

name 參數(shù)
      A.傳字符串

name 參數(shù)可以查找所有名字為 name 的tag,字符串對(duì)象會(huì)被自動(dòng)忽略掉

最簡(jiǎn)單的過(guò)濾器是字符串.在搜索方法中傳入一個(gè)字符串參數(shù),Beautiful Soup會(huì)查找與字符串完整匹配的內(nèi)容,下面的例子用于查找文檔中所有的<b>標(biāo)簽:

soup.find_all('b')
# [<b>The Dormouse's story</b>]

  B.傳正則表達(dá)式

如果傳入正則表達(dá)式作為參數(shù),Beautiful Soup會(huì)通過(guò)正則表達(dá)式的 match() 來(lái)匹配內(nèi)容.下面例子中找出所有以b開(kāi)頭的標(biāo)簽,這表示<body>和<b>標(biāo)簽都應(yīng)該被找到

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

 C.傳列表

如果傳入列表參數(shù),Beautiful Soup會(huì)將與列表中任一元素匹配的內(nèi)容返回.下面代碼找到文檔中所有<a>標(biāo)簽和<b>標(biāo)簽:

soup.find_all(["a", "b"])
# [<b>The Dormouse's story</b>,
# <a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

D.傳 True

True 可以匹配任何值,下面代碼查找到所有的tag,但是不會(huì)返回字符串節(jié)點(diǎn):

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

  E.傳方法

如果沒(méi)有合適過(guò)濾器,那么還可以定義一個(gè)方法,方法只接受一個(gè)元素參數(shù)  ,如果這個(gè)方法返回 True 表示當(dāng)前元素匹配并且被找到,如果不是則反回 False。下面方法校驗(yàn)了當(dāng)前元素,如果包含 class 屬性卻不包含 id 屬性,那么將返回 True:

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

將這個(gè)方法作為參數(shù)傳入 find_all() 方法,將得到所有<p>標(biāo)簽:

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

2)keyword 參數(shù)

如果一個(gè)指定名字的參數(shù)不是搜索內(nèi)置的參數(shù)名,搜索時(shí)會(huì)把該參數(shù)當(dāng)作指定名字tag的屬性來(lái)搜索,如果包含一個(gè)名字為 id 的參數(shù),Beautiful Soup會(huì)搜索每個(gè)tag的”id”屬性:

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

如果傳入 href 參數(shù),Beautiful Soup會(huì)搜索每個(gè)tag的”href”屬性:

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

使用多個(gè)指定名字的參數(shù)可以同時(shí)過(guò)濾tag的多個(gè)屬性:

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

在這里我們想用 class 過(guò)濾,不過(guò) class 是 python 的關(guān)鍵詞,這怎么辦?加個(gè)下劃線就可以:

soup.find_all("a", class_="sister")
# [<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 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

可以通過(guò) find_all() 方法的 attrs 參數(shù)定義一個(gè)字典參數(shù)來(lái)搜索包含特殊屬性的tag:

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

3)text 參數(shù)

通過(guò) text 參數(shù)可以搜搜文檔中的字符串內(nèi)容.與 name 參數(shù)的可選值一樣, text 參數(shù)接受 字符串 , 正則表達(dá)式 , 列表, 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"]

4)limit 參數(shù)

find_all() 方法返回全部的搜索結(jié)構(gòu),如果文檔樹(shù)很大那么搜索會(huì)很慢.如果我們不需要全部結(jié)果,可以使用 limit 參數(shù)限制返回結(jié)果的數(shù)量.效果與SQL中的limit關(guān)鍵字類似,當(dāng)搜索到的結(jié)果數(shù)量達(dá)到 limit 的限制時(shí),就停止搜索返回結(jié)果.

文檔樹(shù)中有3個(gè)tag符合搜索條件,但結(jié)果只返回了2個(gè),因?yàn)槲覀兿拗屏朔祷財(cái)?shù)量:

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

5)recursive 參數(shù)

調(diào)用tag的 find_all() 方法時(shí),Beautiful Soup會(huì)檢索當(dāng)前tag的所有子孫節(jié)點(diǎn),如果只想搜索tag的直接子節(jié)點(diǎn),可以使用參數(shù) recursive=False:

soup.html.find_all("title")
# [<title>The Dormouse's story</title>]
 
soup.html.find_all("title", recursive=False)

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

它與 find_all() 方法唯一的區(qū)別是 find_all() 方法的返回結(jié)果是值包含一個(gè)元素的列表,而 find() 方法直接返回結(jié)果

(3)find_parents()  find_parent()

find_all() 和 find() 只搜索當(dāng)前節(jié)點(diǎn)的所有子節(jié)點(diǎn),孫子節(jié)點(diǎn)等. find_parents() 和 find_parent() 用來(lái)搜索當(dāng)前節(jié)點(diǎn)的父輩節(jié)點(diǎn),搜索方法與普通tag的搜索方法相同,搜索文檔搜索文檔包含的內(nèi)容

(4)find_next_siblings()  find_next_sibling()

這2個(gè)方法通過(guò) .next_siblings 屬性對(duì)當(dāng) tag 的所有后面解析的兄弟 tag 節(jié)點(diǎn)進(jìn)行迭代, find_next_siblings() 方法返回所有符合條件的后面的兄弟節(jié)點(diǎn),find_next_sibling() 只返回符合條件的后面的第一個(gè)tag節(jié)點(diǎn)

(5)find_previous_siblings()  find_previous_sibling()

這2個(gè)方法通過(guò) .previous_siblings 屬性對(duì)當(dāng)前 tag 的前面解析的兄弟 tag 節(jié)點(diǎn)進(jìn)行迭代, find_previous_siblings()方法返回所有符合條件的前面的兄弟節(jié)點(diǎn), find_previous_sibling() 方法返回第一個(gè)符合條件的前面的兄弟節(jié)點(diǎn)

(6)find_all_next()  find_next()

這2個(gè)方法通過(guò) .next_elements 屬性對(duì)當(dāng)前 tag 的之后的 tag 和字符串進(jìn)行迭代, find_all_next() 方法返回所有符合條件的節(jié)點(diǎn), find_next() 方法返回第一個(gè)符合條件的節(jié)點(diǎn)

(7)find_all_previous() 和 find_previous()

這2個(gè)方法通過(guò) .previous_elements 屬性對(duì)當(dāng)前節(jié)點(diǎn)前面的 tag 和字符串進(jìn)行迭代, find_all_previous() 方法返回所有符合條件的節(jié)點(diǎn), find_previous()方法返回第一個(gè)符合條件的節(jié)點(diǎn)

注:以上(2)(3)(4)(5)(6)(7)方法參數(shù)用法與 find_all() 完全相同,原理均類似。

5.  CSS選擇器

我們?cè)趯?xiě) CSS 時(shí),標(biāo)簽名不加任何修飾,類名前加點(diǎn),id名前加 #,在這里我們也可以利用類似的方法來(lái)篩選元素,用到的方法是 soup.select(),返回類型是 list

(1)通過(guò)標(biāo)簽名查找

print soup.select('title') 
#[<title>The Dormouse's story</title>]
 
print soup.select('a')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

(2)通過(guò)類名查找

print soup.select('.sister')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

(3)通過(guò) id 名查找

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

(4)組合查找

組合查找即和寫(xiě) class 文件時(shí),標(biāo)簽名與類名、id名進(jìn)行的組合原理是一樣的,例如查找 p 標(biāo)簽中,id 等于 link1的內(nèi)容,二者需要用空格分開(kāi):

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

直接子標(biāo)簽查找:

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

(5)屬性查找

查找時(shí)還可以加入屬性元素,屬性需要用中括號(hào)括起來(lái),注意屬性和標(biāo)簽屬于同一節(jié)點(diǎn),所以中間不能加空格,否則會(huì)無(wú)法匹配到:

print soup.select('a[class="sister"]')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
 
print soup.select('a[href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>]
 
#屬性也可以與上述查找方式組合,不在同一節(jié)點(diǎn)的空格隔開(kāi),同一節(jié)點(diǎn)的不加空格:
print soup.select('p a[href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>]
 
#以上的 select 方法返回的結(jié)果都是列表形式,可以遍歷形式輸出,然后用 get_text() 方法來(lái)獲取它的內(nèi)容:
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()

find_all和select的區(qū)別

find_all()對(duì)于屬性的值不是精確匹配的,是模糊匹配。同樣的,find()也是模糊匹配

select()方法使用css定位元素,根據(jù)td標(biāo)簽和class屬性值 精確定位,但是會(huì)查詢出來(lái)所有符合條件的元素,返回一個(gè)列表

關(guān)于BeautifuSoup庫(kù)如何在Python中使用就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI