网站爬取数据无法写入Google Sheets的问题求助及方案咨询
问题诊断与解决方法
核心问题
你的代码里worksheet.append_row(entry)传入的是字典,但append_row要求接收有序列表,字典是无序键值对,gspread无法正确解析成表格行,这就是数据没写入的核心原因。另外不同球员的属性字段可能不一致,直接写入会导致列错位混乱。
解决步骤
1. 统一表头,规范列顺序
先收集所有爬取到的字段,生成统一表头,确保所有数据都对应到正确列;如果表格还没表头,先写入表头。
2. 字典转有序列表
将每个球员的字典数据,按照表头顺序转换成列表,让append_row能正确识别每列对应值。
3. 批量写入优化
循环调用append_row会频繁请求Google API,容易触发限制,用append_rows批量写入更高效。
修改后的完整代码
import requests from bs4 import BeautifulSoup import gspread # 初始化gspread连接 gc = gspread.service_account(filename='creds.json') sh = gc.open_by_key('1TD4YmhfAsnSL_Fwo1lckEbnUVBQB6VyKC05ieJ7PKCw') worksheet = sh.sheet1 def get_links(url): data = [] req_url = requests.get(url) soup = BeautifulSoup(req_url.content, "html.parser") for td in soup.find_all('td', {'data-th': 'Player'}): a_tag = td.a name = a_tag.text player_url = a_tag['href'] print(f"Getting {name}") req_player_url = requests.get(f"https://basketball.realgm.com{player_url}") soup_player = BeautifulSoup(req_player_url.content, "html.parser") div_profile_box = soup_player.find("div", class_="profile-box") row = {"Name": name, "URL": player_url} for p in div_profile_box.find_all("p"): try: key, value = p.get_text(strip=True).split(':', 1) row[key.strip()] = value.strip() except: pass data.append(row) return data urls = ['https://basketball.realgm.com/dleague/players/2022'] # 爬取所有数据 all_data = [] for url in urls: print(f"Getting: {url}") all_data.extend(get_links(url)) if all_data: # 提取所有唯一字段作为表头(优先保留Name和URL在前) headers = ["Name", "URL"] for entry in all_data: for key in entry.keys(): if key not in headers: headers.append(key) # 检查表格是否已有表头,无则写入 existing_headers = worksheet.row_values(1) if not existing_headers: worksheet.append_row(headers) # 将每个字典转换为表头顺序的列表 rows_to_insert = [] for entry in all_data: row = [entry.get(header, "") for header in headers] rows_to_insert.append(row) # 批量写入数据 if rows_to_insert: worksheet.append_rows(rows_to_insert) print(f"成功写入{len(rows_to_insert)}条数据") else: print("未爬取到任何数据")
关键改动说明
- 生成统一表头,确保所有字段都有对应列,避免数据错位
- 将字典转成表头对应顺序的列表,解决
append_row无法识别字典的问题 - 用
append_rows批量写入,减少API调用次数,提升效率同时规避限流风险
内容的提问来源于stack exchange,提问作者Anthony Madle
相关产品推荐
相关产品推荐

