Author
- Hey Guys We Have A Gift For You! Click On The Following Link To Claim Your Gift.
-- Belion
大家好我是作者彼獅,本文是我 PyETL Notes 的系列文,將使用 Python 進行資料分析的套件一一介紹說明,如果有補充的背景知識或其他資訊會附註在資訊欄提供參考,同時我產出自己的技術文章與學習筆記,相關的內容可以參考文末資訊,本魯尚菜,文章僅供參考,若有錯誤煩請多賜教言亦歡迎留言討論,拜謝其臨。
Intro
本篇介紹 BeautifulSoup 第三方套件除了 find()
另外一個 method select()
,承上篇 select 是 css 選擇器,我們可以針對 Web 內容中裝飾不同格式的 css 語法直接篩選,與 find()
相反的是, findAll
是索引所有我們選取的標籤內容、 find
是選取首位標籤,而 select
預設是索引所有我們選取的標籤,而 select_one
則是索引首位。
而我們在進行標籤定位時,由於 id 標籤只會對應到整個網頁中唯一的內容,因此我們會優先定位 id 簡潔化我們索引的內容之外,id 所帶標籤本身的內容通常也是前端人員方便清楚識別的內容,所以我們在檢視程式時也更方便。
Code
import requests
from bs4 import BeautifulSoup
url = 'https://www.ptt.cc/bbs/Lifeismoney/index.html'
userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
headers = {
'User-Agent': userAgent
}
res = requests.get(url=url, headers=headers)
html = res.text
# print(html)
soup = BeautifulSoup(html, 'html.parser')
# print(soup)
# slect() 使用 id 定位與 findAll() 寫法無異
# slect('tag') 調用所有符合 tag 的物件,selece_one() 則與 find() 相同只有第一個符合之物件。
logo = soup.select('a', {'id': 'logo'})
logo = soup.select('a', id='logo')
print(logo[0])
print(logo[0].text)
print('https://www.ptt.cc' + logo[0]['href'])
content = soup.select('div', class_='bbs-content')
# print(content[0])
board = content[0].select_one('a', class_="board")
print(board)
# select() 直接定位標籤 return list
board_text = soup.select('.board')
print(board_text)
# select() 直接定位標籤 return str
board_text = soup.select_one('.board')
print(board_text)
print('https://www.ptt.cc' + board_text['href'])
# 直接定位標籤中的標籤。
title = soup.select('head title')
print(title)
Other info
Hola guys! 感謝客官您的閱讀,
如果我的文章對您有幫助或有所獲的話,歡迎關注我的 CoderBridge 帳號與 Belion 部落格!
- 系列文的原始碼:Github
- 本系列文持續更新:PyETL notes
- 接續到 PyETL 實作系列文:PyETL 實作指南