You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium Python定位data-row="1"的tr并获取Box Score

Hey there! Sounds like you're just a step away from grabbing that second game's box score data—let's work through this with a couple of straightforward, reliable approaches using Selenium:

Approach 1: Use CSS Selectors to Target the Row First

CSS selectors are perfect for precise attribute matching. First, zero in on the <tr> element with data-row="1", then drill down to its "Box Score" link:

from selenium.webdriver.common.by import By

# Locate the specific row with data-row="1"
target_game_row = driver.find_element(By.CSS_SELECTOR, 'tr[data-row="1"]')

# Find the Box Score link *within that row* (avoids matching links from other rows)
box_score_link = target_game_row.find_element(By.LINK_TEXT, "Box Score")

# From here, you can either click the link or extract its URL
box_score_url = box_score_link.get_attribute("href")
# Or click it directly: box_score_link.click()

This works because tr[data-row="1"] exactly matches the row you want, and searching within that element ensures you don't accidentally grab the first game's link.

Approach 2: One-Step XPath Targeting

If you prefer a single locator, XPath can target the link directly by combining the row attribute and link text:

from selenium.webdriver.common.by import By

# Directly locate the Box Score link inside the data-row="1" row
box_score_link = driver.find_element(By.XPATH, '//tr[@data-row="1"]//a[text()="Box Score"]')

# Use the link as needed
box_score_link.click()

Pro Tip: Handle Dynamic Loading

If the page loads games dynamically (e.g., via JavaScript), add a wait to make sure the row exists before trying to interact with it:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wait up to 10 seconds for the target row to appear
target_game_row = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, 'tr[data-row="1"]'))
)

# Then grab the Box Score link
box_score_link = target_game_row.find_element(By.LINK_TEXT, "Box Score")

This prevents "element not found" errors caused by trying to interact with elements before they've finished loading.

内容的提问来源于stack exchange,提问作者LUIS MONTEALEGRE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:07:01