Crawlee+Playwright爬取:定位器未找到时设默认值并续爬
解决Playwright定位器未找到时设置默认值的问题
问题核心是Playwright的textContent()方法在定位器未匹配到元素时会抛出异常,而Crawlee默认会对抛出异常的请求进行重试,最终终止URL爬取。要实现“未找到时设默认值并继续”,需要避免未处理的异常抛出,以下是两种可行方案:
方案一:用try/catch单独捕获每个字段的异常
对每个字段的获取逻辑单独包裹try/catch,捕获元素不存在时的错误,直接设置默认值:
let region: string | null = null; let farm: string | null = null; const productDescriptionContainer = page.locator('div[class="product-details__product-description"]'); // 处理Región字段 try { region = await productDescriptionContainer .locator("p") .filter({ hasText: "Región:" }) .textContent(); } catch { region = "未知区域"; // 按需求设置默认值,也可以设为null } // 处理Finca字段 try { farm = await productDescriptionContainer .locator("p") .filter({ hasText: "Finca:" }) .textContent(); } catch { farm = "未知农场"; }
方案二:先检查元素是否存在再获取内容
通过count()方法判断定位器是否匹配到元素,避免触发异常:
const productDescriptionContainer = page.locator('div[class="product-details__product-description"]'); // 获取Región字段 const regionLocator = productDescriptionContainer .locator("p") .filter({ hasText: "Región:" }); const region = (await regionLocator.count() > 0) ? await regionLocator.textContent() : "未知区域"; // 获取Finca字段 const farmLocator = productDescriptionContainer .locator("p") .filter({ hasText: "Finca:" }); const farm = (await farmLocator.count() > 0) ? await farmLocator.textContent() : "未知农场";
为什么之前的方法不生效?
- 使用
||运算符无效:因为textContent()在元素不存在时会直接抛出错误,不会返回undefined或null,所以||逻辑根本不会执行。 - 仅初始化变量但未捕获异常:初始化变量无法阻止
textContent()抛出的异常,Crawlee仍会捕获到未处理的异常并触发重试。
内容的提问来源于stack exchange,提问作者Estratachuela
相关产品推荐
相关产品推荐

