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

拥有回忆 提交于 2021-02-07 09:45:49

问题


I am using the Python module gspread to try and extract a link inside an href tag from a cell of a Google spreadsheet. I have tried the following, and noted their problems:

  1. worksheet.acell ('B5').value: Gets cell text, not link inside href tag.
  2. worksheet.acell ('B5', value_render_option='FORMULA').value: Gets cell text, not link inside href tag.
  3. worksheet.acell('B5').input_value: Returned none. Also, deprecated.

How can I correctly get a link inside href tags from a cell in a Google spreadsheet?


回答1:


In order to retrieve a hyperlink of a cell, it is required to use the method of spreadsheets.get in Sheets API using the fields. Unfortunately, I couldn't find this method in gspread. So in this answer, I would like to propose the following flow.

  1. Retrieve the access token.
    • I think that in this case, the script of your authorization for gspread can be used.
  2. Request to the method of spreadsheets.get in Sheets API using requests module.
  3. Retrieve the hyperlink.

Sample script:

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)
  • This sample script retrieves the hyperlink in the cell "A1" on "Sheet1".

Note:

  • Recently, Google Spreadsheet got to be able to have multiple hyperlinks in a cell. But in the current stage, unfortunately, it seems that those links cannot be retrieved using Sheets API. I believe that this will be resolved in the future update.
  • So, in this sample script, when one hyperlink is set in one cell, this script can retrieve the hyperlink. So please be careful this.

Reference:

  • Method: spreadsheets.get


来源:https://stackoverflow.com/questions/62780104/get-link-inside-href-tag-from-cell-in-google-spreadsheet-gspread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!