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

使用Selenium抓取维基百科表格出现SyntaxError语法错误如何修复

语法错误修复方案

核心错误原因

ignore_index=True是pandas append()方法的入参,你错误将其放在了字典的花括号{}内部,而字典要求所有元素必须遵循键名:值的格式,单独写ignore_index=True不符合字典语法规则,因此触发SyntaxError。

直接修复代码

将ignore_index=True移到字典右括号外侧,作为append()方法的参数即可,修改后的循环段代码如下:

for i in range(len(building)):
    df_building = df_building.append({
        'Building': building[i].text,
        'City': city[i].text,
        'Country': country[i].text,
        'Height in M': height_meters[i].text,
        'Height in Ft': height_ft[i].text,
        'Floors': floors[i].text
    }, ignore_index=True)

其他潜在问题修复建议

  • XPath路径中的"是HTML转义字符,需要替换为普通双引号才能正确匹配页面元素,修改示例:
    building = driver.find_elements_by_xpath('//table[@class="wikitable sortable jquery-tablesorter"][1]/tbody/tr/td[2]')
  • Windows系统下的文件路径使用单斜杠时会触发转义识别,建议给路径字符串加前缀r避免异常,驱动初始化代码修改为:
    driver = webdriver.Chrome(r'C:\Program Files\Python39\chromedriver.exe')
  • 如果你使用pandas 2.0及以上版本,DataFrame.append()已被正式弃用,更推荐用列表收集数据后一次性生成DataFrame,运行效率更高,写法参考:
    data_list = []
    for i in range(len(building)):
        data_list.append({
            'Building': building[i].text,
            'City': city[i].text,
            'Country': country[i].text,
            'Height in M': height_meters[i].text,
            'Height in Ft': height_ft[i].text,
            'Floors': floors[i].text
        })
    df_building = pd.DataFrame(data_list)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:27:01