Author
- Hey Guys We Have A Gift For You! Click On The Following Link To Claim Your Gift.
-- Belion
大家好我是作者彼獅,本文是我 PyETL Notes 的系列文,將使用 Python 進行資料分析的套件一一介紹說明,如果有補充的背景知識或其他資訊會附註在資訊欄提供參考,同時我產出自己的技術文章與學習筆記,相關的內容可以參考文末資訊,本魯尚菜,文章僅供參考,若有錯誤煩請多賜教言亦歡迎留言討論,拜謝其臨。
Intro
requests 是 python 常用於索取 url 資源的第三方套件,與 urllib.request 的差別除了不能使用 ssl 套件之外,功能相同寫法更簡潔,並且預設編碼是 UTF-8 所以不用再轉碼如下:
# urllib.request 寫法
req = request.Request(url=url, headers=headers)
res = request.urlopen(req)
html = res.read().decode('utf-8')
# requests 寫法
res = requests.get(url, headers=headers)
html = res.text
Code
import requests
from bs4 import BeautifulSoup
url = 'https://www.ptt.cc/bbs/joke/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, headers=headers)
print(type(res))
# 預設編碼與物件相容相對友好,省去轉換的過程。
html = res.text
print(html)
Other info
本文使用到套件的文件 Documents:
Hola guys! 感謝客官您的閱讀,如果我的文章對您有幫助或有所獲的話,歡迎關注我的 CoderBridge 帳號與 Belion 部落格!
- 系列文的原始碼:Github
- 本系列文持續更新:PyETL notes
- 接續到 PyETL 實作系列文:PyETL 實作指南