自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python爬蟲之BeautifulSoup

開發(fā) 后端
Beautiful Soup提供一些簡單的、python式的函數(shù)用來處理導(dǎo)航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數(shù)據(jù),因為簡單,所以不需要多少代碼就可以寫出一個完整的應(yīng)用程序。Beautiful Soup自動將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼。

Python爬蟲之BeautifulSoup

簡介

Beautiful Soup提供一些簡單的、python式的函數(shù)用來處理導(dǎo)航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數(shù)據(jù),因為簡單,所以不需要多少代碼就可以寫出一個完整的應(yīng)用程序。Beautiful Soup自動將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然后,你僅僅需要說明一下原始編碼方式就可以了。

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

安裝

  1. pip install BeautifulSoup4 
  2.  
  3. 或 
  4.  
  5. easy_install BeautifulSoup4 

 

創(chuàng)建BeautifulSoup對象

首先應(yīng)該導(dǎo)入BeautifulSoup類庫

  1. from bs4 import BeautifulSoup 

下面開始創(chuàng)建對像,在開始之前為了方便演示,先創(chuàng)建一個html文本,如下:

  1. html = ""
  2.  
  3. <html><head><title>The Dormouse's story</title></head> 
  4.  
  5. <body> 
  6.  
  7. <p class="title" name="dromouse"><b>The Dormouse's story</b></p> 
  8.  
  9. <p class="story">Once upon a time there were three little sisters; and their names were 
  10.  
  11. <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, 
  12.  
  13. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and 
  14.  
  15. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; 
  16.  
  17. and they lived at the bottom of a well.</p> 
  18.  
  19. <p class="story">...</p> 
  20.  
  21. ""

 

創(chuàng)建對象:soup=BeautifulSoup(html,’lxml’),這里的lxml是解析的類庫,目前來說個人覺得***的解析器了,一直在用這個,安裝方法:

  1. pip install lxml 

Tag

Tag就是html中的一個標(biāo)簽,用BeautifulSoup就能解析出來Tag的具體內(nèi)容,具體的格式為soup.name,其中name是html下的標(biāo)簽,具體實例如下:

  1. print soup.title # 輸出title標(biāo)簽下的內(nèi)容,包括此標(biāo)簽,這個將會輸出<title>The Dormouse's story</title> 
  2.  
  3. print soup.head 

 

注意:

這里的格式只能獲取這些標(biāo)簽的***個,后面會講到獲取多個標(biāo)簽的方法。其中對于Tag有兩個重要的屬性name和attrs,分別表示名字和屬性,介紹如下:

  • name:對于Tag,它的name就是其本身,如soup.p.name就是p
  • attrs是一個字典類型的,對應(yīng)的是屬性-值,如print soup.p.attrs,輸出的就是{‘class’: [‘title’], ‘name’: ‘dromouse’},當(dāng)然你也可以得到具體的值,如print soup.p.attrs[‘class’],輸出的就是[title]是一個列表的類型,因為一個屬性可能對應(yīng)多個值,當(dāng)然你也可以通過get方法得到屬性的,如:print soup.p.get(‘class’)。還可以直接使用print soup.p[‘class’]

get

get方法用于得到標(biāo)簽下的屬性值,注意這是一個重要的方法,在許多場合都能用到,比如你要得到<img src=”#”>標(biāo)簽下的圖像url,那么就可以用soup.img.get(‘src’),具體解析如下:

  1. print soup.p.get("class") #得到***個p標(biāo)簽下的src屬性 

string

得到標(biāo)簽下的文本內(nèi)容,只有在此標(biāo)簽下沒有子標(biāo)簽,或者只有一個子標(biāo)簽的情況下才能返回其中的內(nèi)容,否則返回的是None具體實例如下:

  1. print soup.p.string #在上面的一段文本中p標(biāo)簽沒有子標(biāo)簽,因此能夠正確返回文本的內(nèi)容         
  2.  
  3. print soup.html.string  #這里得到的就是None,因為這里的html中有很多的子標(biāo)簽 

 

get_text()

可以獲得一個標(biāo)簽中的所有文本內(nèi)容,包括子孫節(jié)點的內(nèi)容,這是最常用的方法

搜索文檔樹

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

find_all是用于搜索節(jié)點中所有符合過濾條件的節(jié)點

1. name參數(shù):是Tag的名字,如p,div,title …..

soup.find_all("p") 查找所有的p標(biāo)簽,返回的是[<b>The Dormouse's story</b>],可以通過遍歷獲取每一個節(jié)點,如下:

  1. ps=soup.find_all("p"
  2.  
  3. for p in ps: 
  4.  
  5.     print p.get('class')   #得到p標(biāo)簽下的class屬性 

 

傳入正則表達式:soup.find_all(re.compile(r’^b’)查找以b開頭的所有標(biāo)簽,這里的body和b標(biāo)簽都會被查到

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

  1. soup.find_all(["a""b"]) 

2. KeyWords參數(shù),就是傳入屬性和對應(yīng)的屬性值,或者一些其他的表達式

  • soup.find_all(id='link2'),這個將會搜索找到所有的id屬性為link2的標(biāo)簽。傳入正則表達式soup.find_all(href=re.compile("elsie")),這個將會查找所有href屬性滿足正則表達式的標(biāo)簽
  • 傳入多個值:soup.find_all(id='link2',class_='title') ,這個將會查找到同時滿足這兩個屬性的標(biāo)簽,這里的class必須用class_傳入?yún)?shù),因為class是python中的關(guān)鍵詞
  • 有些屬性不能通過以上方法直接搜索,比如html5中的data-*屬性,不過可以通過attrs參數(shù)指定一個字典參數(shù)來搜索包含特殊屬性的標(biāo)簽,如下:
  1. # [<div data-foo="value">foo!</div>] 
  2.  
  3. data_soup.find_all(attrs={"data-foo""value"})   #注意這里的atts不僅能夠搜索特殊屬性,亦可以搜索普通屬性      
  4.  
  5. soup.find_all("p",attrs={'class':'title','id':'value'})  #相當(dāng)與soup.find_all('p',class_='title',id='value'

 

3. text參數(shù):通過 text 參數(shù)可以搜搜文檔中的字符串內(nèi)容.與 name 參數(shù)的可選值一樣, text 參數(shù)接受 字符串 , 正則表達式 , 列表, True

  1. soup.find_all(text="Elsie"
  2.  
  3. # [u'Elsie'
  4.  
  5. soup.find_all(text=["Tillie""Elsie""Lacie"]) 
  6.  
  7. # [u'Elsie', u'Lacie', u'Tillie'
  8.  
  9. soup.find_all(text=re.compile("Dormouse")) 
  10.  
  11. [u"The Dormouse's story", u"The Dormouse's story"

 

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

文檔樹中有3個tag符合搜索條件,但結(jié)果只返回了2個,因為我們限制了返回數(shù)量,代碼如下:

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

 

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

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

它與 find_all() 方法唯一的區(qū)別是 find_all() 方法的返回結(jié)果是值包含一個元素的列表,而 find() 方法直接返回結(jié)果,就是直接返回***匹配到的元素,不是列表,不用遍歷,如soup.find("p").get("class")

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

  1. print soup.select('title'
  2.  
  3. #[<title>The Dormouse's story</title>] 
  4.   
  5.  
  6. print soup.select('a'
  7.  
  8. #[<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>] 

 

通過類名查找

  1. print soup.select('.sister'
  2.  
  3. #[<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名查找

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

 

組合查找

學(xué)過 css 的都知道 css 選擇器,如 p #link1 是查找 p 標(biāo)簽下的 id 屬性為 link1 的標(biāo)簽

  1. print soup.select('p #link1')    #查找p標(biāo)簽中內(nèi)容為id屬性為link1的標(biāo)簽 
  2.  
  3. #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>] 
  4.  
  5.   
  6.  
  7. print soup.select("head > title")   #直接查找子標(biāo)簽 
  8.  
  9. #[<title>The Dormouse's story</title>] 

 

屬性查找

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

  1. print soup.select('a[class="sister"]'
  2.  
  3. #[<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>] 
  4.   
  5.  
  6. print soup.select('a[href="http://example.com/elsie"]'
  7.  
  8. #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>] 

 

同樣,屬性仍然可以與上述查找方式組合,不在同一節(jié)點的空格隔開,同一節(jié)點的不加空格,代碼如下:

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

 

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

  1. soup = BeautifulSoup(html, 'lxml'
  2. print type(soup.select('title')) 
  3.  
  4. print soup.select('title')[0].get_text() 
  5.   
  6.  
  7. for title in soup.select('title'): 
  8.  
  9.     print title.get_text() 

 

責(zé)任編輯:龐桂玉 來源: Python開發(fā)者
相關(guān)推薦

2025-04-22 09:39:46

Python爬蟲網(wǎng)頁數(shù)據(jù)抓取

2017-09-19 15:17:09

PythonBeautifulso爬取網(wǎng)站

2023-09-05 07:55:56

Python網(wǎng)絡(luò)爬蟲

2017-06-07 10:00:56

PythonBeautifulSo解析器

2023-11-28 08:34:39

Python工具

2022-07-03 10:43:23

JS逆向破解

2017-08-09 15:27:33

python爬蟲開發(fā)工具

2019-01-08 10:29:12

BeautifulSoPython第三庫

2018-08-08 11:40:24

ScrapyRequest網(wǎng)絡(luò)爬蟲

2022-01-27 10:26:07

Python

2017-08-22 17:30:14

Python爬蟲

2024-11-27 06:31:02

2021-12-10 19:26:43

Python腳本電子書

2021-01-12 11:26:44

數(shù)據(jù)安全爬蟲

2020-10-19 19:25:32

Python爬蟲代碼

2024-05-31 12:31:54

C#爬蟲Python

2017-06-19 15:32:39

Python爬蟲音頻數(shù)據(jù)

2024-12-30 00:01:00

多模態(tài)大模型Python

2016-11-07 15:23:37

Python

2018-01-11 10:20:04

Python爬蟲豆瓣音樂
點贊
收藏

51CTO技術(shù)棧公眾號