使用Selenium爬取Flashscore指定赛事页面主客队名称的技术问询
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

