Python 3 ดึงข้อมูล html จากเว็บไซต์กีฬา
Oct 11 2020
ฉันพยายามดึงข้อมูลจากเว็บไซต์กีฬาและจนถึงตอนนี้ก็ล้มเหลว ฉันพยายามสกัด 35, ยิงเข้าประตูและ 23 แต่ล้มเหลว
<div class="statTextGroup">
<div class="statText statText--homeValue">35</div>
<div class="statText statText--titleValue">Shots on Goal</div>
<div class="statText statText--awayValue">23</div></div>
from bs4 import BeautifulSoup
import requests
result = requests.get("https://www.scoreboard.com/uk/match/lvbns58C/#match-statistics;0")
src = result.content
soup = BeautifulSoup(src, 'html.parser')
stats = soup.find("div", {"class": "tab-statistics-0-statistic"})
print(stats)
นี่คือรหัสที่ฉันพยายามใช้และเมื่อเรียกใช้ฉันได้รับ "ไม่มี" พิมพ์มาให้ฉัน มีใครช่วยพิมพ์ข้อมูลให้หน่อยได้ไหม
พบเต็มหน้าที่นี่: https://www.scoreboard.com/uk/match/lvbns58C/#match-statistics;0
คำตอบ
AlexandraDudkina Oct 11 2020 at 14:02
เนื่องจากเว็บไซต์แสดงผลโดยจาวาสคริปต์ตัวเลือกที่เป็นไปได้จะโหลดหน้าโดยใช้ซีลีเนียมจากนั้นแยกวิเคราะห์ด้วย BeautifulSoup:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
# initialize selenium driver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('<<PATH_TO_SELENIUMDRIVER>>', options=chrome_options)
# load page via selenium
wd.get("https://www.scoreboard.com/uk/match/lvbns58C/#match-statistics;0")
# wait 30 seconds until element with class mainGrid will be loaded
table = WebDriverWait(wd, 30).until(EC.presence_of_element_located((By.ID, 'statistics-content')))
# parse content of the table
soup = BeautifulSoup(table.get_attribute('innerHTML'), 'html.parser')
print(soup)
# close selenium driver
wd.quit()