我想要与以下定位器交互

<select name="ship[0][596211][address]" id="ship_0_596211_address" class="" title=""></select>

使用下面这行代码:

await page.locator('#ship_0_596211_address').selectOption('24553');

我的问题是,596211是一个动态值,对于每个流来说都是不同的,所以我使用硬编码值的代码行永远不会起作用.如何使用动态值与此特定定位器交互?

考虑到页面上还有其他类似的定位器,我需要哪行代码:

<select name="ship[1][596211][address]" id="ship_1_596211_address" class="" title=""></select>

推荐答案

如果在所有select个元素中都存在name属性,则可以使用wildcard selectors in css来匹配动态值.类似于:

await page.locator('select[name^="ship[0]["][name$="[address]"]').selectOption('24553');

What it means?

  1. select[name^="ship[0]["][name$="[address]"]-以name属性以ship[0]开头、以[address]结尾的所有select元素为目标.

下面,我在htmlcss中创建了一个小示例,它描述了它以预期的select为目标,并对其应用了样式.在剧作家中,您可以使用它来定位您的元素.

select[name^="ship[0]["][name$="[address]"] {
  /*Try changing above to select[name^="ship[1]["][name$="[address]"]. 
for applying style to second select. */
  width: 100%;
  max-width: 300px;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  appearance: none;
  background-color: #fff;
  margin-bottom: 10px;
}

select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
<select name="ship[0][596211][address]" id="ship_0_596211_address" class="" title="">
  <option value="24551">Address 1</option>
  <option value="24552">Address 2</option>
  <option value="24553">Address 3</option>
</select>

<select name="ship[1][596211][address]" id="ship_1_596211_address" class="" title="">
  <option value="24551">Address 5</option>
  <option value="24552">Address 6</option>
  <option value="24553">Address 7</option>
</select>

Javascript相关问答推荐

如何访问Json返回的ASP.NET Core 6中的导航图像属性

Cookie中未保存会话数据

. NET中Unix时间转换为日期时间的奇怪行为

JQuery. show()工作,但. hide()不工作

如何在 cypress 中使用静态嵌套循环

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

Next.js服务器端组件请求,如何发送我的cookie token?

当输入字段无效时,我的应用程序不会返回错误

Web Crypto API解密失败,RSA-OAEP

连接到游戏的玩家不会在浏览器在线游戏中呈现

有条件重定向到移动子域

为什么我的自定义元素没有被垃圾回收?

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

React:防止useContext重新渲染整个应用程序或在组件之间共享数据而不重新渲染所有组件

在单击按钮时生成多个表单时的处理状态

对不同目录中的Angular material 表列进行排序

$GTE的mongoose 问题

如何使pdf.js上的文本呈现为可选?

为什么我的Reaction组件不能使用createBrowserRouter呈现?