Google Sheets用IMPORTXML抓取wine-searcher.com数据出现could not fetch URL错误求助
报错根本原因
该错误并非由URL长度或格式导致,是wine-searcher站点配置了反爬虫防护策略,可识别Google Sheets IMPORTXML函数的默认爬虫请求标识,直接拦截访问,因此修改协议、域名前缀、XPath路径均无法解决问题。
针对Google Sheets的兼容解决方案
可通过自定义Google Apps Script函数绕过默认请求标识限制,操作步骤如下:
- 打开目标表格,点击顶部菜单栏「扩展程序」>「Apps Script」进入脚本编辑器
- 删除编辑器内默认代码,粘贴如下代码:
function CUSTOM_IMPORTXML(target_url, xpath_query) { const request_options = { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }, muteHttpExceptions: true }; try { const page_response = UrlFetchApp.fetch(target_url, request_options); const page_content = page_response.getContentText(); const xml_document = XmlService.parse(page_content); const xpath_result = XmlService.getNamespaceManager().getXPathResult( xpath_query, xml_document.getRootElement(), XmlService.XPathResultType.ORDERED_NODE_SNAPSHOT_TYPE ); const output = []; for (let i = 0; i < xpath_result.getLength(); i++) { output.push(xpath_result.snapshotItem(i).getText().trim()); } return output.length > 1 ? output : output[0]; } catch (e) { return "抓取失败:" + e.toString(); } }
- 点击「保存项目」,授权脚本访问权限后返回表格
- 替换原有公式使用即可:
- 抓取h1标题:
=CUSTOM_IMPORTXML("https://www.wine-searcher.com/find/robert+mondavi+rsrv+cab+sauv+napa+valley+county+north+coast+california+usa","//h1") - 抓取平均价格:
=CUSTOM_IMPORTXML("https://www.wine-searcher.com/find/robert+mondavi+rsrv+cab+sauv+napa+valley+county+north+coast+california+usa","//*[@id='tab-info']/div/div[1]/div[2]/div/div[1]/span[2]/span[2]")
注意:控制抓取频率,短时间内大量请求会被站点临时封禁IP
免费替代方案(若上述方案失效)
- 本地Python爬虫:使用
requests+lxml库自定义请求头抓取数据,导出为CSV后导入Google Sheets,参考代码如下:
import requests from lxml import etree REQUEST_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } target_url = "https://www.wine-searcher.com/find/robert+mondavi+rsrv+cab+sauv+napa+valley+county+north+coast+california+usa" response = requests.get(target_url, headers=REQUEST_HEADERS) html_tree = etree.HTML(response.text) # 提取标题 wine_title = html_tree.xpath("//h1/text()")[0].strip() # 提取平均价格 average_price = html_tree.xpath("//*[@id='tab-info']/div/div[1]/div[2]/div/div[1]/span[2]/span[2]/text()")[0].strip() print(f"酒款名称:{wine_title},平均价格:{average_price}")
- 无代码爬虫工具:使用支持自定义请求头的免费无代码爬虫工具抓取数据,导出为表格格式后导入Google Sheets即可。
内容的提问来源于stack exchange,提问作者Curtis H
相关产品推荐
相关产品推荐

