Python无SharePoint根站点权限访问子站点及SharePlum 403报错解决
问题根因
- 你当前调用的SharePlum接口默认访问SharePoint旧式SOAP接口
/_vti_bin/lists.asmx,该接口需要子站点的列表操作权限,仅持有只读访问权限会触发403报错,和根站点权限无关 - Office365类的第一个参数仅识别SharePoint根域名,填写子站点地址不会生效,认证逻辑是全局的,只要你的账号对子站点有权限,认证后生成的cookie可直接用于子站点资源访问
- 额外注意:SharePlum的原生能力是操作SharePoint后台存储的列表数据,无法直接读取站点页面(SitePages)里嵌入的普通HTML表格,哪怕权限校验通过也拿不到你需要的目标数据
你需要的是页面内嵌HTML表格数据,直接用requests + BeautifulSoup爬取解析即可,示例代码如下:
import requests from bs4 import BeautifulSoup from shareplum import Office365 # 认证参数填根域名即可,不需要根站点权限 authcookie = Office365( 'https://abc.sharepoint.com', username='username@abc.com', password='password' ).GetCookies() # 直接请求你的目标表格页面地址 target_url = "https://mysharepoint.sharepoint.com/sites/mySite/sitepages/tables" resp = requests.get(target_url, cookies=authcookie) resp.raise_for_status() # 解析HTML提取表格 soup = BeautifulSoup(resp.text, 'html.parser') # 按需定位页面里的表格,示例取页面第一个table元素 target_table = soup.find('table') # 转成二维列表格式 table_data = [] for row in target_table.find_all('tr'): row_data = [cell.get_text(strip=True) for cell in row.find_all(['th', 'td'])] if row_data: table_data.append(row_data) print(table_data)
如果你的目标数据是SharePoint后台原生列表,不是页面内嵌HTML表格,可以用O365库调用官方REST API,避免旧式SOAP接口的权限限制,示例代码如下:
from O365 import Account # 认证参数为你在Azure AD注册的应用凭证 credentials = ('client_id', 'client_secret') account = Account(credentials, auth_flow_type='password', username='username@abc.com', password='password') if account.authenticate(scopes=['https://abc.sharepoint.com/.default']): site = account.sharepoint().get_site('mysharepoint.sharepoint.com', '/sites/mySite') target_list = site.get_list('列表名称') # 读取列表所有项 items = target_list.get_items() print(items)
内容的提问来源于stack exchange,提问作者Lophyre
相关产品推荐
相关产品推荐

