ดึงผลหวยจากเว็บ Sanook ด้วย Code 11 บรรทัด

ดึงผลหวยจากเว็บ Sanook.com ด้วย BeautifulSoup และ requests แบบไม่ใช้ selenium

pip install beautifulsoup4
import requests
from bs4 import BeautifulSoup
url = "https://news.sanook.com/lotto/"
response = requests.request("GET", url)
soup = BeautifulSoup(response.text)
# รางวัลที่ 1
first_prize = soup.select_one("#lotto-highlight-result > span:nth-child(1) > strong").text
print({
    "first_prize":first_prize
})

จากนั้นทำซ้ำไปเรื่อยๆกัน รางวัลที่เราต้องการ จนครบทั้งหมด

Code เต็มทั้งหมดครับ หรือทดสอบได้ที่นี้ “ดึงผลหวยจากเว็บ Sanook ด้วย beautifulsoup4 และ requests.ipynb

import requests
from bs4 import BeautifulSoup

url = "https://news.sanook.com/lotto/"

response = requests.request("GET", url)

soup = BeautifulSoup(response.text)

# รางวัลที่ 1
first_prize = soup.select_one("#lotto-highlight-result > span:nth-child(1) > strong").text

# เลขหน้า 3 ตัว
first_3_digits_01 = soup.select_one("#lotto-highlight-result > span:nth-child(2) > b:nth-child(1)").text
first_3_digits_02 = soup.select_one("#lotto-highlight-result > span:nth-child(2) > b:nth-child(2)").text

# เลขท้าย 3 ตัว
last_3_digits_01 = soup.select_one("#lotto-highlight-result > span:nth-child(3) > b:nth-child(1)").text
last_3_digits_02 = soup.select_one("#lotto-highlight-result > span:nth-child(3) > b:nth-child(2)").text

# เลขท้าย 2 ตัว
last_2_digits = soup.select_one("#lotto-highlight-result > span:nth-child(4) > strong").text


print({
    "รางวัลที่ 1":first_prize,
    "เลขหน้า 3 ตัว":[first_3_digits_01,first_3_digits_02],
    "เลขท้าย 3 ตัว":[last_3_digits_01,last_3_digits_02],
    "เลขท้าย 2 ตัว":last_2_digits
})