Python爬蟲庫BeautifulSoup獲取對象(標籤)名,屬性,內容,註釋

如何利用Python爬蟲庫BeautifulSoup獲取對象(標籤)名,屬性,內容,註釋等操做下面就爲你們介紹一下
1、Tag(標籤)對象css

1.Tag對象與XML或HTML原生文檔中的tag相同。html

from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>','lxml')
tag = soup.b
type(tag)

bs4.element.Tag
1
2.Tag的Name屬性bash

每一個tag都有本身的名字,經過.name來獲取網絡

tag.name
1
'b'
1
tag.name = "blockquote" # 對原始文檔進行修改
tag
1
2
<blockquote class="boldest">Extremely bold</blockquote>
1
3.Tag的Attributes屬性學習

獲取單個屬性code

tag['class']
1
['boldest']
1
按字典的方式獲取所有屬性xml

tag.attrs
1
{'class': ['boldest']}
1
添加屬性htm

tag['class'] = 'verybold'
tag['id'] = 1
print(tag)

<blockquote class="verybold" id="1">Extremely bold</blockquote>
1
刪除屬性對象

del tag['class']
del tag['id']
tag

<blockquote>Extremely bold</blockquote>
1.Tag的多值屬性blog

多值屬性會返回一個列表

css_soup = BeautifulSoup('<p class="body strikeout"></p>','lxml')
print(css_soup.p['class'])
1
2
['body', 'strikeout']
1
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>','lxml')
print(rel_soup.a['rel'])
rel_soup.a['rel'] = ['index', 'contents']
print(rel_soup.p)

['index']
<p>Back to the <a rel="index contents">homepage</a></p>

若是轉換的文檔是XML格式,那麼tag中不包含多值屬性

xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml')
xml_soup.p['class']

```bash

‘body strikeout’

2、可遍歷字符串(NavigableString)

1.字符串常被包含在tag內,使用NavigableString類來包裝tag中的字符串

```bash
from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>','lxml')
tag = soup.b
print(tag.string)
print(type(tag.string))

Extremely bold
<class 'bs4.element.NavigableString'>

2.一個 NavigableString 字符串與Python中的str字符串相同,經過str() 方法能夠直接將 NavigableString 對象轉換成str字符串

unicode_string = str(tag.string)
print(unicode_string)
print(type(unicode_string))

Extremely bold
<class 'str'>
1.tag中包含的字符串不能編輯,可是能夠被替換成其它的字符串,用 replace_with() 方法

tag.string.replace_with("No longer bold")
tag

<b class="boldest">No longer bold</b>
1
3、BeautifulSoup對象 BeautifulSoup 對象表示的是一個文檔的所有內容。

大部分時候,能夠把它看成 Tag 對象,它支持 遍歷文檔樹 和 搜索文檔樹 中描述的大部分的方法。

4、註釋與特殊字符串(Comment)對象

markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup,'lxml')
comment = soup.b.string
type(comment)

bs4.element.Comment
1
Comment 對象是一個特殊類型的 NavigableString 對象

comment
1
'Hey, buddy. Want to buy a used parser?'

注意:不少人學Python過程當中會遇到各類煩惱問題解決不了。爲此小編建了個Python全棧免費答疑交流.裙 :624440745,不懂的問題有老司機解決裏面還有最新Python教程項目可拿,,一塊兒相互監督共同進步!
本文的文字及圖片來源於網絡加上本身的想法,僅供學習、交流使用,不具備任何商業用途,版權歸原做者全部,若有問題請及時聯繫咱們以做處理。

原文出處:https://www.cnblogs.com/shabge/p/12341395.html

相關文章
相關標籤/搜索