You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Playwright的locator.textContent()结合正则提取餐厅名称?

使用Playwright提取餐厅名称

针对你给出的HTML结构,这里有几种直接提取餐厅名称的实用方法:

方法一:字符串分割提取

先获取目标元素的完整文本,再通过冒号分割拿到后半段内容:

// JavaScript 示例
const fullText = await page.locator('.card-title').textContent();
const restaurantName = fullText.split(': ')[1].trim();

方法二:浏览器端直接处理(evaluate)

通过evaluate在浏览器环境里直接处理元素文本,减少本地字符串操作:

const restaurantName = await page.locator('.card-title').evaluate(el => {
  return el.textContent.split(': ')[1].trim();
});

方法三:正则匹配(适配格式变化)

如果后续文本格式有微调,正则匹配会更灵活:

const fullText = await page.locator('.card-title').textContent();
const matchResult = fullText.match(/Name: (.*)/);
const restaurantName = matchResult ? matchResult[1].trim() : '';

提取到名称后,直接用于断言即可,比如:

expect(restaurantName).toBe('New Restaurant');

内容的提问来源于stack exchange,提问作者akwasiijunior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 07:29:53