我正在嘗試從所有看起來像這樣的頁面(每個玩家一個)中抓取一些橄欖球統計資料: https ://www.unitedrugby.com/clubs/benetton/filippo-alongi
這只是一個例子。
首先,我使用 selenium 設定了一個驅動程式,然后將內容傳遞給 BeautifulSoup 進行 html 探索。
url = "https://www.unitedrugby.com/clubs/benetton/filippo-alongi"
driver = webdriver.Chrome( options=chrome_options)
driver.get(url)
soup = driver.page_source
soup = BeautifulSoup(soup, 'html.parser')
driver.quit()
此時,我想獲取以下類:player-hero__info-wrap. 我用 來做到這一點find_all(),它可以找到大多數東西,但不是全部。
通過單擊我提供的鏈接并檢查重量值(118KG),您將在檢查器中非常靠近此標簽,因此您可以看到它存在。
但是,刮的時候,我看不到它。我正在使用 selenium,因為此頁面似乎需要在閱讀之前使用 javascript 呈現,但我仍然看不到所有類。
我嘗試添加以下行來執行 javascript:
driver.execute_script("return document.documentElement.outerHTML;")
甚至:
driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
但什么都沒有。
有人可以幫我拿這門課嗎?
uj5u.com熱心網友回復:
這是獲取該資訊的一種方法,僅使用 selenium(為什么要決議頁面兩次?):
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('disable-notifications')
chrome_options.add_argument("window-size=1280,720")
webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
wait = WebDriverWait(browser, 20)
url = 'https://www.unitedrugby.com/clubs/benetton/filippo-alongi'
browser.get(url)
try:
wait.until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))).click()
print('accepted cookies')
except Exception as e:
print('no cookie button!')
player_stats = wait.until (EC.element_to_be_clickable((By.CSS_SELECTOR, 'div[]')))
print(player_stats.text)
### do other stuff, get other info, etc etc ###
browser.quit()
這將點擊消除煩人的 cookie 彈出視窗(在您的場景中可能不需要,但以防萬一您嘗試與頁面互動),并在終端中列印:
accepted cookies
AGE
22
HEIGHT
6'0''
WEIGHT
118KG
使用 Selenium 時,您并不真的需要 BeautifulSoup,因為它具有強大的定位器和查找方法。有關檔案,請訪問https://www.selenium.dev/documentation/
編輯:這是基于 requests/BeautifulSoup 的另一種解決方案:
import requests
from bs4 import BeautifulSoup as bs
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}
url = 'https://www.unitedrugby.com/clubs/benetton/filippo-alongi'
r = requests.get(url, headers=headers)
soup = bs(r.text, 'html.parser')
player_data = soup.select_one('div.player-hero__info-wrap')
print(player_data.text.strip())
結果:
Age
22
Height
6'0''
Weight
118KG
相關檔案:https ://beautiful-soup-4.readthedocs.io/en/latest/index.html用于 BeautifulSoup 和請求:https ://requests.readthedocs.io/en/latest/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/506694.html
標籤:javascript Python 硒 网页抓取 美丽的汤
