如何使用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
相关产品推荐
相关产品推荐

