簡體   English   中英

從 Google 電子表格 (gspread) 中的單元格獲取 href 標記內的鏈接

[英]Get link inside href tag from cell in Google Spreadsheet (gspread)

我正在使用 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 標簽內的鏈接?

為了檢索單元格的超鏈接,需要使用表格 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 電子表格能夠在一個單元格中包含多個超鏈接。 但不幸的是,在當前階段,似乎無法使用表格 API 檢索這些鏈接。 我相信這將在未來的更新中得到解決。
  • 因此,在此示例腳本中,當在一個單元格中設置一個超鏈接時,此腳本可以檢索超鏈接。 所以請注意這一點。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM