使用Python從維基百科資訊框中提取文字
在這篇文章中,我們將使用Python中的BeautifulSoup和requests庫來抓取維基百科資訊框中的文字。我們可以在10分鐘內完成,非常簡單。
我們需要安裝bs4和requests。執行以下命令進行安裝。
pip install bs4 pip install requests
按照以下步驟編寫程式碼,以提取我們想要的資訊框文字。
- 匯入bs4和requests模組。
- 使用requests.get()方法向要從中提取資料的頁面傳送HTTP請求。
- 使用bs4.BeautifulSoup類解析響應文字,並將其儲存在一個變數中。
- 訪問維基百科頁面並檢查所需的元素。
- 使用bs4提供的合適方法查詢元素。
讓我們看看下面的示例程式碼。
示例
# importing the module
import requests
import bs4
# URL
URL = "https://en.wikipedia.org/wiki/India"
# sending the request
response = requests.get(URL)
# parsing the response
soup = bs4.BeautifulSoup(response.text, 'html')
# Now, we have paresed HTML with us. I want to get the _motto_ from the wikipedia page.
# Elements structure
# table - class="infobox"
# 3rd tr to get motto
# getting infobox
infobox = soup.find('table', {'class': 'infobox'})
# getting 3rd row element tr
third_tr = infobox.find_all('tr')[2]
# from third_tr we have to find first 'a' element and 'div' element to get required data
first_a = third_tr.div.find('a')
div = third_tr.div.div
# motto
motto = f"{first_a.text} {div.text[:len(div.text) - 3]}"
# printing the motto
print(motto)如果執行上述程式,您將得到以下結果。
輸出
Satyameva Jayate "Truth Alone Triumphs"
結論
您可以透過檢查維基百科頁面並查詢元素來獲取任何想要的資料。如果您對本教程有任何疑問,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP