【问题标题】:Get link inside href tag from cell in Google Spreadsheet (gspread)从 Google 电子表格 (gspread) 中的单元格获取 href 标记内的链接
【发布时间】:2026-01-10 18:10:02
【问题描述】:

我正在使用 Python 模块 gspread 尝试从 Google 电子表格的单元格中提取 href 标记内的链接。我尝试了以下方法,并注意到了他们的问题:

  1. worksheet.acell ('B5').value:获取单元格文本,而不是href标签内的链接。
  2. worksheet.acell ('B5', value_render_option='FORMULA').value:获取单元格文本,而不是href标签内的链接。
  3. worksheet.acell('B5').input_value:没有返回。此外,已弃用。

如何从 Google 电子表格的单元格中正确获取 href 标记内的链接?

【问题讨论】:

  • 嘿@Tanaike,你已经回答了相关问题。但这不是我问题的直接答案。但它对其他会看这篇文章的人很有用。
  • @Tanaike 关于我的解决方案。我在另一列中找到了具有确切直接链接而不是超链接的列。这不是这个问题的解决方案,它只是我的问题的替代方案。
  • 感谢您的回复。我能理解它。所以我想取消删除我的答案。当这对用户有用时,我很高兴。
  • 感谢您的贡献和参与 :)
  • @Tanaike 能否请您对我的问题展开悬赏。如果可能的话!

标签: python gspread


【解决方案1】:

为了检索单元格的超链接,需要使用 Sheets API 中的电子表格.get 方法使用字段。不幸的是,我在gspread 中找不到这种方法。所以在这个答案中,我想提出以下流程。

  1. 检索访问令牌。
    • 我认为在这种情况下,可以使用您对gspread的授权脚本。
  2. 使用 requests 模块向 Sheets API 中的电子表格方法请求。
  3. 检索超链接。

示例脚本:

import requests
import urllib.parse


spreadsheetId = "###"  # Please set the Spreadsheet ID.
cellRange = "Sheet1!A1"  # Please set the range with A1Notation. In this case, the hyperlink of the cell "A1" of "Sheet1" is retrieved.

client = gspread.authorize(credentials)  # I think that this is also used in your script for using gsperad.

# 1. Retrieve the access token.
access_token = client.auth.token

# 2. Request to the method of spreadsheets.get in Sheets API using `requests` module.
fields = "sheets(data(rowData(values(hyperlink))))"
url = "https://sheets.googleapis.com/v4/spreadsheets/" + spreadsheetId + "?ranges=" + urllib.parse.quote(cellRange) + "&fields=" + urllib.parse.quote(fields)
res = requests.get(url, headers={"Authorization": "Bearer " + access_token})

# 3. Retrieve the hyperlink.
obj = res.json()
link = obj["sheets"][0]['data'][0]['rowData'][0]['values'][0]['hyperlink']
print(link)
  • 此示例脚本检索“Sheet1”上单元格“A1”中的超链接。

注意:

  • 最近,Google 电子表格必须能够在一个单元格中包含多个超链接。但不幸的是,在当前阶段,似乎无法使用 Sheets API 检索这些链接。我相信这将在未来的更新中得到解决。
  • 因此,在此示例脚本中,当在一个单元格中设置一个超链接时,此脚本可以检索超链接。所以请注意这一点。

参考:

【讨论】:

  • 感谢您的回复。根据我的要求,我选择了其他地方来获取 url。
  • @Chaithanya Krishna 感谢您的回复。我不得不为我糟糕的英语水平道歉。我无法理解As of my requirement, I have chosen some other place to get url.。我可以问你吗?如果我误解了你的问题,我也必须为此道歉。
  • 我说我找到了另一个来源,我可以在其中获取 URL,而不是从超链接文本中获取它。所以,就目前而言,没有问题。感谢您的回复。