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

使用Selenium爬取Flashscore指定赛事页面主客队名称的技术问询

Fix: Duplicate Team Names in Flashscore Selenium Scraper

Ah, I see exactly what's going on here! You're hitting a common XPath pitfall that's making both your home and away team queries return the same name. Let me break down the issue and fix it for you.

The Root Cause

When you use // at the start of an XPath inside a nested find_element call (like _at.find_element_by_xpath('//*[contains(@class, "participantName")]')), it doesn't search within the parent element's subtree—it resets to searching the entire HTML document from the root. That's why both your home and away team calls are grabbing the first matching participantName element (which is the home team's name).

The Fix: Use Relative XPath Paths

Instead of starting with //, use .// to tell Selenium to search relative to the parent element you've already selected. Here's the corrected code:

# 获取主队名称
_ht = driver.find_element_by_xpath('//*[contains(@class, "home")]')
ht = _ht.find_element_by_xpath('.//*[contains(@class, "participantName")]')
_homeName = ht.text

# 获取客队名称
_at = driver.find_element_by_xpath('//*[contains(@class, "away")]')
at = _at.find_element_by_xpath('.//*[contains(@class, "participantName")]')
_awayName = at.text

Even Better: Simplify Your Code

You can skip the nested calls entirely by combining the parent and child selectors into a single XPath. This makes your code cleaner and less error-prone:

# 获取主队名称
_homeName = driver.find_element_by_xpath('//*[contains(@class, "home")]//*[contains(@class, "participantName")]').text

# 获取客队名称
_awayName = driver.find_element_by_xpath('//*[contains(@class, "away")]//*[contains(@class, "participantName")]').text

A Quick Tip for Reliability

For more consistent results, you might want to narrow down the element types (e.g., div instead of *) if you inspect the page's HTML and confirm these elements are always divs. For example:
//div[contains(@class, "home")]//div[contains(@class, "participantName")]

This reduces the chance of matching unintended elements with the same class names elsewhere on the page.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:17:49