Scrape nội dung từ Infobox trang Wikipedia dùng BeautifulSoup và requests.
Cài đặt: pip install bs4 requests.
Các bước: gửi request → parse HTML → tìm table class="infobox" → lấy hàng/thẻ cần thiết.
Ví dụ: Lấy motto của trang India
import requests, 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"
Kết luận
Kiểm tra phần tử (Inspect) trên trang Wikipedia để xác định selector chính xác.