[英]Get link inside href tag from cell in Google Spreadsheet (gspread)
I am using the Python module gspread to try and extract a link inside an href tag from a cell of a Google spreadsheet.我正在使用 Python 模块 gspread 尝试从 Google 电子表格的单元格中提取 href 标记内的链接。 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
:获取单元格文本,而不是 href 标记内的链接。worksheet.acell ('B5', value_render_option='FORMULA').value
: Gets cell text, not link inside href tag. worksheet.acell ('B5', value_render_option='FORMULA').value
:获取单元格文本,而不是链接到 href 标记内。worksheet.acell('B5').input_value
: Returned none. worksheet.acell('B5').input_value
:没有返回。 Also, deprecated. How can I correctly get a link inside href tags from a cell in a Google spreadsheet?如何从 Google 电子表格中的单元格中正确获取 href 标签内的链接?
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.为了检索单元格的超链接,需要使用表格 API 中的电子表格.get 方法使用字段。 Unfortunately, I couldn't find this method in
gspread
.不幸的是,我在
gspread
中找不到这种方法。 So in this answer, I would like to propose the following flow.所以在这个答案中,我想提出以下流程。
gspread
can be used.gspread
的授权脚本。requests
module.requests
模块向 Sheets API 中的电子表格方法请求。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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.