如何使用Python+Selenium从SharePoint Excel文件获取数据?是否需每次下载?
是否必须下载文件?
不是必须的。除了下载本地读取,还有两种更高效的替代方案:
- 直接调用SharePoint的Graph API读取数据,无需依赖Selenium模拟浏览器,速度更快、稳定性更高
- 若文件为SharePoint Online共享文件,可通过
pandas结合requests直接读取在线文件(需处理权限验证)
但如果你的自动化流程必须依赖Selenium完成前置网页操作(比如需先完成表单提交、权限验证等步骤才能访问文件),那么下载文件就是必要环节。
用Python-Selenium实现SharePoint Excel文件下载
以下是基于Chrome浏览器的具体实现步骤和代码:
前置配置
- 确保ChromeDriver版本与本地Chrome浏览器版本完全匹配
- 预先设置浏览器默认下载路径,避免触发保存弹窗
代码示例
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import time # 配置Chrome下载选项 chrome_options = Options() download_dir = "/your/local/download/directory" # 替换为本地实际路径 chrome_options.add_experimental_option("prefs", { "download.default_directory": download_dir, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True }) # 初始化浏览器 driver = webdriver.Chrome(options=chrome_options) # 完成SharePoint登录流程(需根据实际登录页面调整元素定位) driver.get("https://your-sharepoint-site-url.com") # 输入用户名 driver.find_element(By.ID, "i0116").send_keys("your-account@domain.com") driver.find_element(By.ID, "idSIButton9").click() time.sleep(2) # 输入密码 driver.find_element(By.ID, "i0118").send_keys("your-password") driver.find_element(By.ID, "idSIButton9").click() # 关闭"保持登录"弹窗(若有) try: driver.find_element(By.ID, "idBtn_Back").click() except: pass # 导航到文件所在的文档库页面 driver.get("https://your-sharepoint-site-url.com/sites/your-site/documents/target-folder") # 定位并触发下载操作(两种方式选其一) # 方式1:通过文件右侧的"更多选项"菜单下载 more_btn = driver.find_element(By.XPATH, "//div[text()='target-file.xlsx']/ancestor::tr//button[@aria-label='更多选项']") more_btn.click() time.sleep(1) download_btn = driver.find_element(By.XPATH, "//div[text()='下载']") download_btn.click() # 方式2:直接点击文件的下载链接(部分SharePoint版本支持) # download_link = driver.find_element(By.XPATH, "//a[contains(@href, 'target-file.xlsx') and contains(@href, 'download')]") # download_link.click() # 等待文件下载完成(根据文件大小调整等待时长,或用文件监控逻辑替代) time.sleep(10) # 关闭浏览器 driver.quit()
关键注意事项
- SharePoint页面元素的ID、XPath会因版本(Online/本地部署)或站点配置不同而变化,需用浏览器开发者工具实际定位
- 若登录涉及多因素认证(MFA),Selenium无法自动处理,建议改用API方案或结合
msal库完成认证 - 下载完成后,可通过
pandas或openpyxl读取本地文件:
import pandas as pd df = pd.read_excel(f"{download_dir}/target-file.xlsx") print(df.head())
无下载的高效方案(推荐)
若无需Selenium模拟浏览器操作,直接调用Graph API是最优解:
import requests import pandas as pd from io import BytesIO # 获取Graph API访问令牌(需在Azure AD注册应用,获取client_id、client_secret等信息) token_url = "https://login.microsoftonline.com/your-tenant-id/oauth2/v2.0/token" auth_data = { "grant_type": "client_credentials", "client_id": "your-client-id", "client_secret": "your-client-secret", "scope": "https://graph.microsoft.com/.default" } token_response = requests.post(token_url, data=auth_data) access_token = token_response.json()["access_token"] # 调用API读取Excel工作表数据 file_api_url = "https://graph.microsoft.com/v1.0/drives/your-drive-id/items/your-file-id/workbook/worksheets('Sheet1')/usedRange" headers = {"Authorization": f"Bearer {access_token}"} data_response = requests.get(file_api_url, headers=headers) sheet_data = data_response.json() # 转换为DataFrame df = pd.DataFrame(sheet_data["values"][1:], columns=sheet_data["values"][0]) print(df.head())
内容的提问来源于stack exchange,提问作者user9811289
相关产品推荐
相关产品推荐

