如何在BeautifulSoup写入Google Sheets时避免重复URL?
解决Google Sheets爬虫重复写入URL的问题
要避免重复写入已存在于表格C列的URL,你可以通过提前缓存已有URL+写入前存在性检查的方式修改代码,具体实现如下:
核心逻辑
- 先读取表格C列的所有已存URL,存入集合(集合的成员查询效率远高于列表,适合频繁做存在性判断)
- 每次生成新的目标URL后,先检查是否在集合中:
- 若不存在:写入表格,并将该URL加入集合(避免后续循环中重复判断)
- 若存在:直接跳过写入
修改后的完整代码
from cgitb import text import requests from bs4 import BeautifulSoup import gspread import datetime import urllib.parse gc = gspread.service_account(filename='creds.json') sh = gc.open('scrapetosheets').sheet1 # 读取表格中已有的所有URL(C列,对应列表索引2),过滤空值后存入集合 existing_urls = set() all_rows = sh.get_all_values() for row in all_rows: if len(row) >= 3 and row[2].strip(): existing_urls.add(row[2].strip()) urls = ["https://www.ig.com/uk/trading-strategies", "https://www.ig.com/us/trading-strategies"] for url in urls: my_url = requests.get(url) html = my_url.content soup = BeautifulSoup(html, 'html.parser') for item in soup.find_all('h3', class_="article-category-section-title"): date = datetime.datetime.now() title = item.find('a', class_ = 'primary js_target').text.strip() rel_url = item.find('a', class_ = 'primary js_target').get('href') base_url = "https://www.ig.com" full_url = urllib.parse.urljoin(base_url, rel_url) # 检查URL是否已存在,不存在才执行写入 if full_url not in existing_urls: info = {'date':date, 'title':title, 'url':full_url} sh.append_row([str(info['date']), str(info['title']), str(info['url'])]) # 将新URL加入集合,避免后续重复判断 existing_urls.add(full_url)
额外优化说明
- 把原代码中的
abs变量名改为base_url,避免和Python内置函数abs()重名 - 读取已有URL时增加空值过滤,防止表格中C列的空行干扰判断
- 集合
existing_urls仅初始化一次,放在爬取循环之前,减少对Google Sheets的重复请求,提升整体效率
内容的提问来源于stack exchange,提问作者Mark Leach
相关产品推荐
相关产品推荐

