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?
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.
gspread
can be used.requests
module.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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.