- Requests 教程
- Requests - 首頁
- Requests - 概述
- Requests - 環境搭建
- Requests - HTTP請求是如何工作的?
- Requests - 使用Requests
- 處理HTTP請求的響應
- Requests - HTTP請求頭
- Requests - 處理GET請求
- 處理POST、PUT、PATCH和DELETE請求
- Requests - 檔案上傳
- Requests - 使用Cookie
- Requests - 處理錯誤
- Requests - 處理超時
- Requests - 處理重定向
- Requests - 處理歷史記錄
- Requests - 使用會話
- Requests - SSL證書
- Requests - 身份驗證
- Requests - 事件鉤子
- Requests - 代理
- Requests - 使用Requests進行網頁抓取
- Requests 有用資源
- Requests - 快速指南
- Requests - 有用資源
- Requests - 討論
Requests - 使用Requests進行網頁抓取
我們已經瞭解瞭如何使用python requests庫從給定的URL獲取資料。我們將嘗試使用以下方法從Tutorialspoint網站(位於https://tutorialspoint.tw/tutorialslibrary.htm)抓取資料:
- Requests庫
- python的Beautiful Soup庫
我們已經安裝了Requests庫,現在讓我們安裝Beautiful Soup包。如果您想探索Beautiful Soup的更多功能,可以在其官方網站https://www.crummy.com/software/BeautifulSoup/bs4/doc/檢視。
安裝Beautiful Soup
我們將看到如何在下面安裝Beautiful Soup:
E:\prequests>pip install beautifulsoup4 Collecting beautifulsoup4 Downloading https://files.pythonhosted.org/packages/3b/c8/a55eb6ea11cd7e5ac4ba cdf92bac4693b90d3ba79268be16527555e186f0/beautifulsoup4-4.8.1-py3-none-any.whl ( 101kB) |████████████████████████████████| 102kB 22kB/s Collecting soupsieve>=1.2 (from beautifulsoup4) Downloading https://files.pythonhosted.org/packages/81/94/03c0f04471fc245d08d0 a99f7946ac228ca98da4fa75796c507f61e688c2/soupsieve-1.9.5-py2.py3-none-any.whl Installing collected packages: soupsieve, beautifulsoup4 Successfully installed beautifulsoup4-4.8.1 soupsieve-1.9.5
現在我們已經安裝了python requests庫和Beautiful Soup。
現在讓我們編寫程式碼,從給定的URL抓取資料。
網頁抓取
import requests
from bs4 import BeautifulSoup
res = requests.get('https://tutorialspoint.tw/tutorialslibrary.htm')
print("The status code is ", res.status_code)
print("\n")
soup_data = BeautifulSoup(res.text, 'html.parser')
print(soup_data.title)
print("\n")
print(soup_data.find_all('h4'))
使用requests庫,我們可以獲取給定URL的內容,Beautiful Soup庫則有助於解析它並按我們想要的方式獲取詳細資訊。
您可以使用Beautiful Soup庫,透過HTML標籤、類、ID、CSS選擇器以及更多方法來獲取資料。以下是我們獲得的輸出,其中我們列印了頁面的標題以及頁面上的所有h4標籤。
輸出
E:\prequests>python makeRequest.py The status code is 200 <title>Free Online Tutorials and Courses</title> [<h4>Academic</h4>, <h4>Computer Science</h4>, <h4>Digital Marketing</h4>, <h4>Monuments</h4>,<h4>Machine Learning</h4>, <h4>Mathematics</h4>, <h4>Mobile Development</h4>,<h4>SAP</h4>, <h4>Software Quality</h4>, <h4>Big Data & Analytics</h4>, <h4>Databases</h4>, <h4>Engineering Tutorials</h4>, <h4>Mainframe Development</h4>, <h4>Microsoft Technologies</h4>, <h4>Java Technologies</h4>, <h4>XML Technologies</h4>, <h4>Python Technologies</h4>, <h4>Sports</h4>, <h4>Computer Programming</h4>,<h4>DevOps</h4>, <h4>Latest Technologies</h4>, <h4>Telecom</h4>, <h4>Exams Syllabus</h4>, <h4>UPSC IAS Exams</h4>, <h4>Web Development</h4>, <h4>Scripts</h4>, <h4>Management</h4>,<h4>Soft Skills</h4>, <h4>Selected Reading</h4>, <h4>Misc</h4>]
廣告