问题
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:
worksheet.acell ('B5').value
: Gets cell text, not link inside href tag.worksheet.acell ('B5', value_render_option='FORMULA').value
: Gets cell text, not link inside href tag.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.
- Retrieve the access token.
- I think that in this case, the script of your authorization for
gspread
can be used.
- I think that in this case, the script of your authorization for
- Request to the method of spreadsheets.get in Sheets API using
requests
module. - 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