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

如何将Python爬取的加密货币价格数据保存至OneDrive的Excel文件

解决方法

提供两种可用方案,可根据你的使用场景选择:


方案1:使用OneDrive本地同步客户端(零开发成本,普通用户推荐)

  • 首先确保你电脑已经安装并登录OneDrive桌面同步客户端,找到本地OneDrive同步文件夹的路径,Windows系统默认路径为C:\Users\你的系统用户名\OneDrive,Mac系统默认路径为/Users/你的系统用户名/OneDrive
  • 直接修改原有代码最后一行的保存路径为OneDrive同步文件夹路径即可,示例:
    # 替换原有wb.save('moedas.xlsx')为下面的代码,路径改成你本地OneDrive的实际路径
    wb.save(r'C:\Users\xxx\OneDrive\moedas.xlsx')
    
  • 保存完成后OneDrive会自动把文件同步到云端,不需要额外编写连接代码。

方案2:调用微软Graph API直接上传(无本地同步客户端、服务器部署场景适用)

前置准备

  • 到Azure应用注册页面新建一个应用,获取客户端ID、客户端密钥,配置Files.ReadWrite读写权限,拿到访问凭证。
  • 安装所需依赖:pip install msal requests

完整修改后代码

import requests
import re
from bs4 import BeautifulSoup
from openpyxl import Workbook
from io import BytesIO
import msal

# 原有加密货币价格爬取逻辑
coins = ['bitcoin', 'ethereum', 'singularitynet', 'helium', 'cardano', 'vechain', 'polymath-network', 'binance-coin','kin']
wb = Workbook()
ws = wb.active

for coin in coins:
    page = requests.get('https://coinmarketcap.com/pt-br/currencies/' + coin)
    soup = BeautifulSoup(page.text, 'lxml')
    name_of_coin = soup.find('h1', class_='priceHeading').text
    price = soup.find_all('div', class_=re.compile('priceValue'))[0].text[2:]
    char_to_replace = {',': '.',
                       '.': ','}
    price_corrected = price.translate(str.maketrans(char_to_replace))
    ws.append([name_of_coin, price_corrected])

# 将Excel写入内存,无需先存本地
excel_buffer = BytesIO()
wb.save(excel_buffer)
excel_buffer.seek(0)

# 以下参数替换为你自己的Azure应用和OneDrive信息
CLIENT_ID = "你的Azure应用客户端ID"
CLIENT_SECRET = "你的Azure应用客户端密钥"
# 个人OneDrive账号租户ID填common,企业账号填对应租户ID
TENANT_ID = "common"
SCOPES = ["https://graph.microsoft.com/.default"]

# 获取接口访问凭证
app = msal.ConfidentialClientApplication(
    client_id=CLIENT_ID,
    client_credential=CLIENT_SECRET,
    authority=f"https://login.microsoftonline.com/{TENANT_ID}"
)
token_result = app.acquire_token_for_client(scopes=SCOPES)
access_token = token_result["access_token"]

# 上传文件到OneDrive根目录
# 个人账号上传地址用https://graph.microsoft.com/v1.0/me/drive/root:/moedas.xlsx:/content
# 企业账号把xxx@xxx.com替换成你绑定OneDrive的企业邮箱
upload_url = "https://graph.microsoft.com/v1.0/users/xxx@xxx.com/drive/root:/moedas.xlsx:/content"
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
response = requests.put(upload_url, headers=headers, data=excel_buffer)
if response.status_code in (200, 201):
    print("文件上传OneDrive成功")
else:
    print(f"上传失败,状态码:{response.status_code}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:15:04