如何保留超链接爬取表格并上传至Google Sheet?已完成爬取部分
剩余任务完成思路
一、提取表格中的超链接
当前代码用pd.read_html仅获取了表格文本,丢失了超链接,需单独解析表格节点提取链接:
- 遍历目标表格的每一行(
<tr>)和单元格(<td>),对应DataFrame的行列位置 - 对每个单元格检查是否存在
<a>标签:- 若存在,提取
href属性(需拼接域名https://www.marefa.org生成完整链接)和标签内文本 - 可选择在DataFrame中新增列存储链接,或把单元格内容替换为
HYPERLINK(链接, 文本)格式(方便后续导入Google Sheet时直接生效)
- 若存在,提取
- 示例代码片段:
# 遍历表格行提取链接 rows = indiatable.find_all('tr') link_data = [] for row in rows[1:]: # 跳过表头行 cols = row.find_all('td') row_links = [] for col in cols: a_tag = col.find('a') if a_tag: full_link = f"https://www.marefa.org{a_tag.get('href')}" cell_text = a_tag.get_text(strip=True) row_links.append((cell_text, full_link)) else: row_links.append((col.get_text(strip=True), None)) link_data.append(row_links) # 将链接整合到DataFrame,为有链接的列新增对应链接列 for col_idx, col_name in enumerate(df.columns): df[f"{col_name}_链接"] = [item[col_idx][1] for item in link_data]
二、上传数据到Google Sheet
推荐用gspread库结合Google服务账号完成上传:
- 前置准备:
- 登录Google Cloud控制台,创建项目并启用「Google Sheets API」和「Google Drive API」
- 创建服务账号,下载JSON格式的密钥文件
- 打开目标Google Sheet,将服务账号的邮箱地址添加为表格的编辑权限成员
- 代码实现步骤:
- 安装依赖:
pip install gspread oauth2client - 用服务账号密钥初始化gspread客户端
- 将DataFrame数据转为列表格式写入指定Sheet;若要保留超链接,可将单元格内容设为
=HYPERLINK("链接", "文本") - 示例代码片段:
- 安装依赖:
import gspread from oauth2client.service_account import ServiceAccountCredentials # 配置认证范围 scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] # 加载服务账号密钥文件 creds = ServiceAccountCredentials.from_json_keyfile_name('你的密钥文件名.json', scope) client = gspread.authorize(creds) # 打开目标表格(支持通过名称或URL定位) sheet = client.open("你的表格名称").sheet1 # 准备带超链接的写入数据 write_data = [] # 添加表头 write_data.append(df.columns.tolist()) # 处理每行数据 for _, row in df.iterrows(): current_row = [] for col in df.columns: if "_链接" in col: continue link_col = f"{col}_链接" if row[link_col]: current_row.append(f'=HYPERLINK("{row[link_col]}", "{row[col]}")') else: current_row.append(row[col]) write_data.append(current_row) # 清空表格原有内容并写入新数据 sheet.clear() sheet.update('A1', write_data)
内容的提问来源于stack exchange,提问作者Mohamad Abdelsamad
相关产品推荐
相关产品推荐

