从 Google Sheet 检索链接值?

Retrieve value of links from Google Sheet?

我在 Google Sheet 中有一些值,其中一些是 hyperlinked,就像这里的第三个:

我想检索每个单元格的文本值和 hyperlink(如果存在)。

我可以通过 gspread 轻松访问 sheet:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    './credentials.json', scope)
gc = gspread.authorize(credentials)
key = 'xxxxx'
wks = gc.open_by_key(key).worksheets()
for wk in wks:
    links = wk.col_values(3)
    for l in links:
       print l.value

但是,这只会打印 link 的字符串值,而不是 link 指向的实际 href。

有谁知道是否可以使用 gspread 或其他库以编程方式检索它?

gspread 中,一个 Cell 实例有一个未记录的属性 input_value,使您可以访问公式。

>>> formula = mycell.input_value
>>> formula
'=HYPERLINK("https://url.com","Link Text")'
>>> lst = formula.split('"')
>>> lst[1], lst[3]
('https://url.com', 'Link Text')

从那里你只需要拆分字符串以删除不需要的部分。

在您的情况下,您可能希望像这样子类化 gspread.Worksheet

class CustomWorksheet(gspread.Worksheet):
    def get_links(self, col):
        """Returns a list of all links urls in column `col`.
           Empty cells in this list will be rendered as :const:`None`.
        """
        start_cell = self.get_addr_int(1, col)
        end_cell = self.get_addr_int(self.row_count, col)

        row_cells = self.range('%s:%s' % (start_cell, end_cell))
        return [cell.input_value.split('"')[1] for cell in row_cells if cell.input_value.startswith('=HYPERLINK')]