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

使用BeautifulSoup获取FIDE对局图片src属性时的判断问题

问题分析与代码修正

原代码的核心问题

  1. 变量作用域错误:第一个循环中的picture是全局变量,第二个循环复用它时,拿到的始终是最后一行的图片对象,不是当前行的。
  2. 对象类型错误:直接将BeautifulSoup的img Tag对象与HTML字符串比较,两者类型不匹配,即使输出看起来一致,==判断也会失败。正确做法是提取img标签的src属性值来判断。
  3. 逻辑判断错误:if "ID" and "Name" in row这种写法逻辑有问题,应该写成if "ID" in row and "Name" in row,否则只要"Name"在row里就会触发条件。

修正后的代码

第一步:修改数据采集逻辑,存储图片的src属性

for row in rows:
    imgs = row.find_all('img')
    # 提取第一张图片的src,没有则设为空字符串
    img_src = imgs[0]['src'] if imgs else ''
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    cols.append(img_src)  # 存储src而非img对象
    data.append([ele for ele in cols if ele])

第二步:修改判断逻辑,基于src值确定执色

for row in data:
    # 修正逻辑判断的写法
    if "ID" in row and "Name" in row:
        continue
    if 'Round' in row and 'Opp. name' in row:
        continue
    if "Game" in row:
        tempdata = {
            "ID" : row[0],
            "Fed" : row[2],
            "Rating" : row[3]
        }
        continue
    # 从当前行获取图片src(之前append到了cols末尾)
    img_src = row[-1]
    if img_src == '/imga/clr_wh.gif':
        player = 1
        print("player is white")
    elif img_src == '/imga/clr_bl.gif':
        player = 0
        print("player is black")
    else:
        player = 1
        print(img_src)
        print("an error occured")
    print(player)

关键说明

  • 采集数据时不再存储整个img对象,而是直接提取src属性,简化后续判断逻辑。
  • 第二个循环中从当前行的末尾取出src值,确保每一行的判断都对应自身的图片。
  • 修正了逻辑判断的写法,避免无效的跳过逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:45:46