數據提取之bs4(BeautifuSoup4)模塊與Css選擇器

BeautifuSoup4

from bs4 import BeautifulSoup

創建對象 <class 'bs4.BeautifulSoup'>

soup = BeautifulSoup(源碼, '解析器')

bs4標簽種類

(1)tag: 標簽

print(soup.title, type(soup.title))

(2)獲取標簽里面的文本內容, 可導航的字符串,數據類型是<class 'bs4.element.NavigableString'>對象,可以使用字符串的方法

title = soup.title
# string
print(title.string, type(title.string))

(3)注釋

# 注釋 <class 'bs4.element.Comment'>
html = '<b><!--注釋內容--></b>'
soup2 = BeautifulSoup(html, 'lxml')

遍歷文檔樹

# 解析數據
head_tag = soup.p #默認獲取第一個p標簽
# 獲取標簽的子節點, .contents: 返回的是一個所有子節點的列表
# print(head_tag.contents)

print(head_tag.children)? # 返回的是一個生成器對象,通過循環遍歷取值
for head in head_tag.children:
print(head)

源碼:

# 1. 導入模塊
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>
"""# 2. 創建對象  <class 'bs4.BeautifulSoup'>
soup = BeautifulSoup(html_doc, 'lxml')

獲取節點文本內容

.string

# 通過上一級標簽,去獲取子級的標簽文本內容
# head = soup.head
# print(head.string)

.text

# print(head.text)? # 獲取的是多個子級標簽的文本內容,內容都拼接在一起

# strings/stripped_strings
contents = soup.html
# print(contents.string)? # 沒有獲取
# print(contents.text)

.strings


# print(contents.strings)? # <generator object Tag._all_strings at 0x000001E214912820> 生成器對象
# strings可以獲取這個標簽下的所有的文本,文本內容包含很多空行
# for data in contents.strings:
#???? print(data)

.stripped_strings

# stripped_strings可以獲取這個標簽下的所有的文本,去除了多空行
# for data in contents.stripped_strings:
#???? print(data)

總結:

獲取標簽文本內容
string: 標簽里面只有一個標簽有文本內容, 可導航的字符串,(使用 BeautifulSoup 解析文檔后,標簽(Tag)之間的文本會被轉換為NavigableString對象,比如:<p>Hello, World!</p>,其中的"Hello, World!"就是一個NavigableString對象。它之所以被稱為 "可導航",是因為他可以通過它訪問周圍的其他元素(如父標簽、兄弟標簽等),形成一個樹形結構)
text: 將所有的標簽文本內容拼接在一起
strings: 依次獲取所有的標簽文本內容,包含空行, 返回的是一個生成器對象
stripped_strings: 依次獲取所有的標簽文本內容,去除多余的空行看, 返回的是一個生成器對象

獲取父節點

.parent

title_tag = soup.title
print(title_tag)? #<title>The Dormouse's story</title>
print(title_tag.parent)? #<head><title>The Dormouse's story</title></head>

.parents

# 一旦是獲取的是多個標簽內容,返回的就是生成器
a_tag = soup.a
print(a_tag.parents)? ?#<generator object PageElement.parents at 0x0000027F14C502E0>
for p in a_tag.parents:
print(p.name)
'''
p
body
html
[document]
'''

獲取同級節點

源代碼:

from bs4 import BeautifulSouphtml2 = """<a>
<b>bbbb</b><c>ccccc</c><d>dddd</d>
</a>"""soup = BeautifulSoup(html2, 'lxml')
b_tag = soup.c
# print(b_tag.next_sibling)  # 跟他相鄰的下一個節點
# print(b_tag.next_siblings)  # 跟他相鄰的下一個節點print(b_tag.previous_sibling)  # 上一個所有的兄弟節點
print(b_tag.previous_siblings)  # 上一個所有的兄弟節點

.next_sibling/.next_siblings

# print(b_tag.next_sibling)? # 跟他相鄰的下一個節點
# print(b_tag.next_siblings)? # 跟他相鄰的下一個所有節點

.previous_sibling)/.previous_siblings


print(b_tag.previous_sibling)? # 上一個所有的兄弟節點
print(b_tag.previous_siblings)? # 上一個所有的兄弟節點

方法使用(核心)

find(): 查找一個

# 獲取a標簽
a_tag = soup.find('a')? # 默認查找第一個標簽
print(a_tag)


find_all():查找所有

a_tag_all = soup.find_all('a')
print(a_tag_all)? # 返回的是一個列表,用循環遍歷

# 同時找兩個標簽,標簽使用元組或列表使其成為一個整體,不能分開寫
a_p_tag = soup.find_all(('title', 'b'))? ? ? #也可以寫為:a_p_tag = soup.find_all(['title', 'b'])
print(a_p_tag)

案例:

# 導入模塊
from bs4 import BeautifulSouphtml = """
<table class="tablelist" cellpadding="0" cellspacing="0"><tbody><tr class="h"><td class="l" width="374">職位名稱</td><td>職位類別</td><td>人數</td><td>地點</td><td>發布時間</td></tr><tr class="even"><td class="l square"><a target="_blank" href="position_detail.php?id=33824&keywords=python&tid=87&lid=2218">22989-金融云區塊鏈高級研發工程師(深圳)</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-25</td></tr><tr class="odd"><td class="l square"><a target="_blank" href="position_detail.php?id=29938&keywords=python&tid=87&lid=2218">22989-金融云高級后臺開發</a></td><td>技術類</td><td>2</td><td>深圳</td><td>2017-11-25</td></tr><tr class="even"><td class="l square"><a target="_blank" href="position_detail.php?id=31236&keywords=python&tid=87&lid=2218">SNG16-騰訊音樂運營開發工程師(深圳)</a></td><td>技術類</td><td>2</td><td>深圳</td><td>2017-11-25</td></tr><tr class="odd"><td class="l square"><a target="_blank" href="position_detail.php?id=31235&keywords=python&tid=87&lid=2218">SNG16-騰訊音樂業務運維工程師(深圳)</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-25</td></tr><tr class="even"><td class="l square"><a target="_blank" href="position_detail.php?id=34531&keywords=python&tid=87&lid=2218">TEG03-高級研發工程師(深圳)</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-24</td></tr><tr class="odd"><td class="l square"><a target="_blank" href="position_detail.php?id=34532&keywords=python&tid=87&lid=2218">TEG03-高級圖像算法研發工程師(深圳)</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-24</td></tr><tr class="even"><td class="l square"><a target="_blank" href="position_detail.php?id=31648&keywords=python&tid=87&lid=2218">TEG11-高級AI開發工程師(深圳)</a></td><td>技術類</td><td>4</td><td>深圳</td><td>2017-11-24</td></tr><tr class="odd"><td class="l square"><a target="_blank" href="position_detail.php?id=32218&keywords=python&tid=87&lid=2218">15851-后臺開發工程師</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-24</td></tr><tr class="even"><td class="l square"><a target="_blank" href="position_detail.php?id=32217&keywords=python&tid=87&lid=2218">15851-后臺開發工程師</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-24</td></tr><tr class="odd"><td class="l square"><a id="test" class="test" target='_blank' href="position_detail.php?id=34511&keywords=python&tid=87&lid=2218">SNG11-高級業務運維工程師(深圳)</a></td><td>技術類</td><td>1</td><td>深圳</td><td>2017-11-24</td></tr></tbody>
</table>
<a href="https://www.baid.com">百度一下</a>
<a href="https://www.douban.com">豆瓣一下</a>
<a herf="https://www.python.com">python一下</a>
"""# 實例化一個對象
soup = BeautifulSoup(html, 'lxml')# 獲取的是所有的tr標簽
# trs = soup.find_all('tr')# 獲取class="even"標簽, bs4 class屬性定位
# trs = soup.find_all('tr', class_="even")
# trs = soup.find_all('tr', attrs={"class": "even"})
# print(trs)
# <a id="test" class="test"
# a = soup.find_all('a', id="test", class_="test")
# find_all沒有獲取到數據,返回的是一個空列表
# trs = soup.find_all('a', attrs={"class": "test", "id":"test"})
# print(trs)# 獲取所有a標簽里面的href屬性值
# a_lst = soup.find_all('a')
# for a in a_lst:
#     '''
#     get(): 屬性不存在,返回的是一個none
#     對象['屬性名']: 屬性名 不存在,報錯
#     '''
#     # href = a.get('href')
#     href = a['href']
#     print(href)# 獲取職位名稱
trs = soup.find_all('tr')[1:]
for tr in trs:# print(tr)a = tr.find('a')print(a.string)

獲取class="even"標簽, bs4 class屬性定位

# trs = soup.find_all('tr', class_="even")
# trs = soup.find_all('tr', attrs={"class": "even"})
# print(trs)

通過id和屬性定位

# <a id="test" class="test"
# a = soup.find_all('a', id="test", class_="test")
# find_all沒有獲取到數據,返回的是一個空列表
# trs = soup.find_all('a', attrs={"class": "test", "id":"test"})
# print(trs)

獲取所有a標簽里面的href屬性值

get(): 屬性不存在,返回的是一個none
對象['屬性名']: 屬性名 不存在,報錯

# a_lst = soup.find_all('a')
# for a in a_lst:
#???? '''
#???? get(): 屬性不存在,返回的是一個none
#???? 對象['屬性名']: 屬性名 不存在,報錯
#???? '''
#???? # href = a.get('href')
#???? href = a['href']
#???? print(href)

# 獲取職位名稱
trs = soup.find_all('tr')[1:]
for tr in trs:
# print(tr)
a = tr.find('a')
print(a.string)

Css選擇器

select:查找標簽,默認查找所有,并且返回的數據類型list

print(soup.select('a'))? ?#查找所以的a標簽

定位class='sister'的標簽,使用.sister? ? ?.屬性值

print(soup.select('.sister'))

定位id="link1"的標簽,使用#link1

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

定位p標簽并且id值為link1,使用p#link1

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

獲取的title標簽下的文本信息,select: 只有一個元素,返回的數據類型還是列表

print(soup.select('title')[0].string)
print(soup.select('title')[0].text)
print(list(soup.select('title')[0].strings))
print(list(soup.select('title')[0].stripped_strings))

p a: 選擇所有位于<p>元素內a元素,無論嵌套了多少層,都能找到

print(soup.select('p a'))

p>a: 選擇所有作為<p>直接的子元素標簽

print(soup.select('p>a'))

<p class="story">Once upon a time there were three little sisters; and their names were<span><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>,<a href="sister">余承東</a>;and they lived at the bottom of a well.</span>
</p>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/88378.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/88378.shtml
英文地址,請注明出處:http://en.pswp.cn/web/88378.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

CPP中的List

一.list的介紹&#xff1a;1.list是可以在常數范圍內在任意位置進行插入和刪除的序列式容器&#xff0c;并且該容器可以前后雙向迭代。2.list的底層是雙向鏈表結構&#xff0c;帶有哨兵位的頭結點 。3. list與forward_list非常相似&#xff1a;最主要的不同在于forward_list是單…

Ntfs!LfsUpdateLfcbFromRestart函數分析之Ntfs!LfsFindOldestClientLsn

第0部分&#xff1a;//// Find the oldest client Lsn. Use the last flushed Lsn as a starting point.//Lfcb->OldestLsn Lfcb->LastFlushedLsn;LfsFindOldestClientLsn( RestartArea,Add2Ptr( RestartArea, Lfcb->ClientArrayOffset, PLFS_CLIENT_RECORD ),&…

「日拱一碼」021 機器學習——特征工程

目錄 特征選擇 過濾法&#xff08;Filter Methods&#xff09; 方差選擇法 相關系數法 卡方檢驗 包裹法&#xff08;Wrapper Methods&#xff09; 遞歸特征消除&#xff08;RFE&#xff09; 嵌入法&#xff08;Embedded Methods&#xff09; L1正則化&#xff08;Lasso…

k8s:安裝 Helm 私有倉庫ChartMuseum、helm-push插件并上傳、安裝Zookeeper

ChartMuseum 是 Kubernetes 生態中用于存儲、管理和發布 Helm Charts 的開源系統&#xff0c;主要用于擴展 Helm 包管理器的功能 核心功能 ?集中存儲?&#xff1a;提供中央化倉庫存儲Charts&#xff0c;支持版本管理和權限控制。 ? ?跨集群部署?&#xff1a;支持多集群環境…

C++編程學習(第二天)

1、求a和b兩個數之和。#include <iostream> using namespace std;int main() {int a, b, sum; //定義變量a、b、sumcout << "請輸入第一個數字a: "; //打印需要顯示的字符串cin >> a; // >&…

毫米波雷達守護銀發安全:七彩喜跌倒檢測儀重構居家養老防線

在老齡化加速與獨居老人數量攀升的背景下&#xff0c;跌倒已成為威脅老年人生命安全的“隱形殺手”。七彩喜跌倒檢測儀以毫米波雷達技術為核心&#xff0c;通過“非接觸式監測智能預警”重塑居家安全防護體系&#xff0c;為銀發群體構建起全天候、無感化的數字守護網。技術突破…

面試復盤:節流中第二次觸發的事件?答錯補課

面試復盤&#xff1a;節流中第二次觸發的事件&#xff1f;答錯補課 背景描述 今天面試時被問到一個看似基礎但暗藏玄機的問題&#xff1a;“節流&#xff08;Throttle&#xff09;函數中&#xff0c;第二次觸發的那一幀事件是否會被丟掉&#xff1f;” 我基于對經典節流實現的…

Spark偽分布式集群搭建(Ubuntu系統)

環境準備 系統要求&#xff1a;Ubuntu 20.04/22.04 LTS 軟件版本&#xff1a; Hadoop 3.3.5 JDK 8 Spark-3.5.6-bin-hadoop3 硬件要求&#xff1a;至少4GB內存&#xff0c;20GB磁盤空間 以下是基于Ubuntu系統的Spark偽分布式集群搭建全流程。以Spark 3.5.6 Hadoop 3.3.…

【快手】數據挖掘面試題0001:查找連續三天登錄的用戶

文章大綱一、測試數據構建二、自連接方案三、窗口函數方案一張用戶表&#xff0c;uer_id&#xff0c;signin_date&#xff0c;大概是這么幾項&#xff0c;查找連續三天登錄的用戶。 比如說&#xff0c;1,2兩天登錄不是連續三天&#xff0c;456登錄為連續三天登錄&#xff0c;56…

簡說scp命令

簡單介紹 scp的全稱是&#xff1a;Secure Copy Protocol&#xff08;安全復制協議&#xff09;&#xff0c;是Linux中用于在網絡中安全傳輸文件的命令行工具。它基于SSH協議&#xff0c;用于在本地服務器和遠程服務器之間&#xff0c;或者兩臺遠程服務器之間復制文件或目錄。 s…

自動化測試解決方案Parasoft SOAtest無腳本UI測試實踐指南

傳統UI自動化測試常面臨技術門檻高、維護成本大、穩定性差等挑戰。尤其在頁面頻繁變更時&#xff0c;測試腳本的更新和維護會顯著降低測試效率。 自動化測試解決方案Parasoft SOAtest通過可視化操作和智能元素定位技術&#xff0c;無需編寫代碼&#xff0c;讓測試人員能夠像真…

vscode配置頭文件和編譯器

在 VS Code 中配置編譯器和頭文件路徑需要修改兩個核心文件&#xff1a;c_cpp_properties.json&#xff08;用于智能提示&#xff09;和 tasks.json&#xff08;用于構建&#xff09;。以下是詳細步驟&#xff1a; —### 1. 配置智能提示和頭文件路徑 (c_cpp_properties.json)作…

HTML+JS+CSS制作一個數獨游戲

閑來無事&#xff0c;用HTMLJSCSS制作了一個數獨游戲消遣。其實主要是自己做題的時候用筆畫刪除數字太容易出錯&#xff0c;所以想搞一個程序稍微輔助一下。通過制作這個程序&#xff0c;反而提高了手工做題的水平&#xff0c;至少學會了記錄步數以便于回退。 20250710功能更新…

嵌入式硬件中電容的基本原理與實現詳解02

我們今天重點討論點知識點如下: 1.各種種類的電容優缺點對比講解 2.電容的標稱值介紹 3.電容的單位介紹 4.常見的電壓信號有哪些? 5. 電容的耐壓值講解 6.電容的容值有哪些? 7.12pF、15pF 電容常用在什么場合? 8. 振蕩電路中使用的電容常常需要使用什么材質的電容? 9.100n…

Python訓練打卡DAY46

DAY46&#xff1a;通道注意力&#xff08;SE注意力&#xff09; 恩師浙大疏錦行 知識點&#xff1a; 不同CNN層的特征圖&#xff1a;不同通道的特征圖什么是注意力&#xff1a;注意力家族&#xff0c;類似于動物園&#xff0c;都是不同的模塊&#xff0c;好不好試了才知道。通…

fastadmin_php專項

1.時間的判斷,還有就是在php這邊如何去拿前端html元素上面的值input($row.borrowtime);// 創建兩個 DateTime 對象$row_expecttime new \DateTime(input($row.borrowtime));$par_expecttime new \DateTime( $params[expecttime]); // // 計算兩個日期之間的差異 // …

如何在MySQL中選擇使用InnoDB還是MyISAM引擎?

在 MySQL 中選擇 InnoDB 還是 MyISAM 存儲引擎時&#xff0c;需根據應用場景的需求權衡功能、性能和數據完整性。以下是具體的選擇指南&#xff1a; 1. 優先考慮事務和外鍵需求必須使用 InnoDB&#xff1a; 若應用需要 事務支持&#xff08;如金融轉賬、訂單處理&#xff09;或…

邀請函 | 知從科技邀您共赴2025 RISC-V 中國峰會

第五屆RISC-V中國峰會將于2025年7月16至19日在上海張江科學會堂隆重舉辦&#xff0c;本屆峰會由上海開放處理器產業創新中心&#xff08;SOPIC&#xff09;主辦&#xff0c;RISC-V國際開源實驗室&#xff08;RIOS實驗室&#xff09;和上海張江高科技園區開發股份有限公司聯合主…

企業數字化轉型規劃和建設方案(管理架構、應用架構、技術架構)PPT

一、戰略定位與核心目標以 “技術賦能業務&#xff0c;數據驅動創新” 為核心思路&#xff0c;構建 “三步走” 戰略演進路徑&#xff0c;實現 IT 從 “基礎支撐” 到 “戰略引擎” 的升級&#xff1a;IT1.0&#xff08;1-2 年&#xff09;&#xff1a;夯實基礎能力定位 “穩健…

基于Uniapp+MySQL+PHP的景區多商戶小程序源碼系統 帶完整的搭建指南

溫馨提示&#xff1a;文末有資源獲取方式該系統采用 PHP MySQL 的經典開發組合。PHP 作為一種廣泛使用的開源腳本語言&#xff0c;具有簡單易學、運行速度快、跨平臺性強等優點&#xff0c;能夠快速開發出功能強大的 Web 應用程序。MySQL 則是一款穩定可靠的關系型數據庫管理系…