Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ดึงข้อความจาก Infobox ของ Wikipedia ด้วย Python

ใช้ BeautifulSoup และ requests ดึงข้อมูลจาก Infobox หน้า Wikipedia

ขั้นตอน

  1. ติดตั้ง: pip install bs4 requests
  2. Request หน้าเว็บ
  3. Parse ด้วย BeautifulSoup
  4. Inspect หา element ใน Infobox (table class="infobox")
  5. Extract ข้อมูลที่ต้องการ

ตัวอย่าง: ดึง Motto ของหน้า India

import requests
import bs4

URL = "https://en.wikipedia.org/wiki/India"
response = requests.get(URL)
soup = bs4.BeautifulSoup(response.text, 'html.parser')

infobox = soup.find('table', {'class': 'infobox'})
third_tr = infobox.find_all('tr')[2]

first_a = third_tr.div.find('a')
div = third_tr.div.div

motto = f"{first_a.text} {div.text[:len(div.text) - 3]}"
print(motto)
# Satyameva Jayate "Truth Alone Triumphs"

สรุป

Inspect element ใน browser แล้วใช้ find/find_all ดึงข้อมูลได้ทุกอย่าง