網頁抓取:缺少 href 屬性 - 需要模擬滑鼠點擊進行網頁抓取嗎?
P粉550823577
P粉550823577 2024-04-04 10:32:06
0
1
3474

對於一個有趣的網頁抓取項目,我想從 ttps://www.nhl.com/stats/teams 收集 NHL 資料。

有一個可點擊的 Excel 匯出標籤,我可以使用 seleniumbs4 找到它。

不幸的是,事情到這裡就結束了: 由於沒有 href 屬性,我似乎無法存取資料。

我透過使用 pynput 模擬滑鼠點擊得到了我想要的,但我想知道:

我可以採取不同的做法嗎?如果感覺很笨拙。

-> 帶有匯出圖示的標籤可以在這裡找到:

a class="styles__ExportIcon-sc-16o6kz0-0 dIDMgQ"

-> 這是我的程式碼

`import pynput
from pynput.mouse import Button, Controller
import time

from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome(executable_path = 'somepath\chromedriver.exe')

URL = 'https://www.nhl.com/stats/teams'

driver.get(URL)
html = driver.page_source  # DOM with JavaScript execution complete
soup = BeautifulSoup(html)
body = soup.find('body')
print(body.prettify())


mouse = Controller()

time.sleep(5) # Sleep for 5 seconds until page is loaded
mouse.position = (1204, 669) # thats where the icon is on my screen
mouse.click(Button.left, 1) # executes download`

P粉550823577
P粉550823577

全部回覆(1)
P粉807471604

沒有href屬性,透過JS觸發下載。使用 selenium 時找到您的元素並使用 .click() 下載檔案:

driver.find_element(By.CSS_SELECTOR,'h2>a').click()

在這裡使用css 選擇器 來取得直接子級 的<a>

或透過以styles__E​​xportIcon開頭的類別直接選擇它:

driver.find_element(By.CSS_SELECTOR,'a[class^="styles__ExportIcon"]').click()

範例

您可能需要處理 onetrust 橫幅,因此請先按一下它,然後下載該表。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

url = 'https://www.nhl.com/stats/teams'
driver.get(url)
driver.find_element(By.CSS_SELECTOR,'#onetrust-reject-all-handler').click()
driver.find_element(By.CSS_SELECTOR,'h2>a').click()
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!