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

网页爬取:为何for循环未遍历完整女足世界杯比赛结果列表?

问题分析与修复

你的代码只输出一场结果就停止,核心原因是变量名错误:循环中遍历的变量是score,但后续查找比分和客队时误用了未定义的x,程序运行到这里会直接抛出NameError中断执行,所以只输出了第一场比赛的主队名称就停止了。

另外,比分部分你重复调用了同一个选择器,其实需要分别获取两支球队的得分,同时建议增加异常处理避免因页面结构变化导致报错。

修复后的代码如下:

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.skysports.com/womens-world-cup-results')
soup = BeautifulSoup(source.text, 'html.parser')

scores = soup.find_all('div', class_='fixres__body')

for score in scores:
    # 获取主队名称
    team1 = score.find('span', class_='matches__item-col matches__participant matches__participant--side1')
    # 获取客队名称
    team2 = score.find('span', class_='matches__item-col matches__participant matches__participant--side2')
    # 获取两队比分
    scores_sides = score.find_all('span', class_='matches__teamscores-side')
    
    # 确保元素存在再输出,避免报错
    if team1 and team2 and len(scores_sides) == 2:
        print(f"{team1.text.strip()} {scores_sides[0].text.strip()} - {scores_sides[1].text.strip()} {team2.text.strip()}")

修复要点

  • 统一使用循环变量score进行元素查找,替换未定义的x
  • 用find_all获取两个比分元素,分别对应主队和客队得分
  • 增加非空判断,避免页面结构变化导致的AttributeError

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:07:43