使用SharePlum连接SharePoint列表报错:list index out of range求助
核心问题定位
你遇到的"list index out of range"错误,主要原因是传入Site()的SHAREPOINT_SITE参数错误——你用了列表的前端页面URL(AllItems.aspx),但SharePlum要求传入的是SharePoint站点的根URL,而非列表的访问页面。
具体修复步骤
1. 修正站点URL
将SHAREPOINT_SITE改为站点的根地址,比如:
SHAREPOINT_SITE = 'https://***********.com/sites/PowerApp/'
不要包含列表相关的路径或参数。
2. 修复函数内的变量依赖问题
你的authenticate函数定义了user_name和password参数,但内部直接使用了全局变量USERNAME和PASSWORD,这会导致参数传入失效,改为使用函数参数:
authcookie = Office365(sp_url, username=user_name, password=password).GetCookies()
3. 优化异常捕获(可选但推荐)
裸except会隐藏具体错误类型,建议捕获特定异常并打印完整栈信息,方便排查:
import traceback try: # ... 原有认证逻辑 ... except Exception as e: print('Failed to connect to SP site: {}'.format(e)) traceback.print_exc() # 打印完整错误栈
4. 正确获取列表实例
认证成功后,需要通过站点实例获取列表,而不是在站点URL中直接指定列表:
# 认证成功后添加这行代码获取列表 sp_list = sp_site.List(SHAREPOINT_LIST)
修正后的完整代码示例
import sys import requests from bs4 import BeautifulSoup from shareplum.site import Version from shareplum import Site, Office365 import traceback SHAREPOINT_URL = 'https://***************.com/' SHAREPOINT_SITE = 'https://***********.com/sites/PowerApp/' # 修正为站点根URL SHAREPOINT_LIST = 'changed_class_schedule' USERNAME = '*****************************' PASSWORD = '****************' def authenticate(sp_url, sp_site, user_name, password): """ Takes a SharePoint url, site url, username and password to access the SharePoint site. Returns a SharePoint Site instance if passing the authentication, returns None otherwise. """ site = None try: authcookie = Office365(sp_url, username=user_name, password=password).GetCookies() site = Site(sp_site, version=Version.v365, authcookie=authcookie, verify_ssl=True) except Exception as e: print('Failed to connect to SP site: {}'.format(e)) traceback.print_exc() return site # Test the function sp_site = authenticate(SHAREPOINT_URL, SHAREPOINT_SITE, USERNAME, PASSWORD) if sp_site: # 获取列表 sp_list = sp_site.List(SHAREPOINT_LIST) print("成功连接并获取列表")
额外排查点
- 确认账号拥有目标站点和列表的访问权限
- 如果是SharePoint Online,确保账号启用了基本认证(部分租户可能需要开启)
- 若遇到SSL验证问题,可临时将
verify_ssl改为False测试(不建议生产环境使用)
内容的提问来源于stack exchange,提问作者Quân Đoàn
相关产品推荐
相关产品推荐

