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

使用Openpyxl向xlsx工作表写入数据时触发ValueError报错

报错原因

触发报错的核心原因是openpyxl不支持直接将Python列表类型写入Excel单元格。
你代码中赋值给单元格的ig_get_present是列表对象,哪怕列表内仅包含1个链接字符串,也不属于Excel单元格支持的基础数据类型(字符串、数值、布尔值、时间类型等),和报错信息里提示的Cannot convert ['https://www.instagram.com/xxxx/'] to Excel完全对应。

顺带提一个代码里的不规范写法:循环for ig_get in ig_get:会覆盖外层定义的ig_get列表变量,虽然当前场景下不会触发逻辑错误,但变量名重名很容易埋下隐性bug,建议改成不同的变量名。

修复方案

根据你的存储需求二选一调整赋值逻辑即可:

  • 仅存储匹配到的第一条Instagram链接:取列表首个元素写入,提前加判空逻辑,避免页面无匹配链接时触发索引越界错误
  • 存储页面匹配到的所有Instagram链接:将列表拼接为分隔符分隔的字符串后写入,可选择逗号、换行符作为分隔符,设置单元格自动换行后即可正常展示全部链接

修改后的可运行代码片段如下:

column_name = 'URL'
column_name2 = 'Instagram'

headers = [cell.value for cell in sheet[1]]

col = get_column_letter(headers.index(column_name) + 1)
col2 = headers.index(column_name2) + 1

for cell in sheet[col][1:]:
    url = cell.value
    r = requests.get(url)
    ig_keywords = ['instagram.com']
    ig_get_present = []
    soup = BeautifulSoup(r.content, 'html5lib')
    all_links = soup.find_all('a', href=True)
    for keyword in ig_keywords:
        for link in all_links:
            if keyword in link.attrs['href']:
                ig_get_present.append(link.attrs['href'])
    # 方案1:只存第一条链接,无匹配时留空
    # sheet.cell(cell.row, col2).value = ig_get_present[0] if ig_get_present else ""
    # 方案2:换行分隔存所有匹配链接
    sheet.cell(cell.row, col2).value = "\n".join(ig_get_present)

内容的提问来源于stack exchange,提问作者Kal-Toh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:09:29