ในบทความนี้ เราจะขูดข้อความจากกล่องข้อมูลของ Wikipedia โดยใช้ BeatifulSoup และคำขอใน Python เราสามารถทำได้ใน 10 นาที ตรงไปตรงมา
เราจำเป็นต้องติดตั้ง bs4 และคำขอ ดำเนินการคำสั่งด้านล่างเพื่อติดตั้ง
pip install bs4 pip install requests
ทำตามขั้นตอนด้านล่างเพื่อเขียนโค้ดเพื่อดึงข้อความที่เราต้องการจากกล่องข้อมูล
- นำเข้า bs4 และร้องขอโมดูล
- ส่งคำขอ HTTP ไปยังหน้าที่คุณต้องการดึงข้อมูลโดยใช้เมธอด Request.get()
- แยกวิเคราะห์ข้อความตอบกลับโดยใช้คลาส bs4.BeautifulSoup และเก็บไว้ในตัวแปร
- ไปที่หน้า Wikipedia และตรวจสอบองค์ประกอบที่คุณต้องการ
- ค้นหาองค์ประกอบโดยใช้วิธีการที่เหมาะสมจาก 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"
บทสรุป
คุณสามารถรับข้อมูลที่ต้องการได้โดยการตรวจสอบและค้นหาองค์ประกอบในหน้า Wikipedia หากคุณมีคำถามใดๆ เกี่ยวกับบทแนะนำ โปรดระบุในส่วนความคิดเห็น