如何使用 Playwright 获取下拉框中所选选项

9
我是使用Playwright的C#语言绑定。
示例HTML:
<select id="txtType" name="Type" class="form-control">
        <option>Blog Posts</option>
        <option>Books</option>
        <option>Presentations</option>
        <option>Videos</option>
        <option>Podcasts</option>
        <option>Examples</option>
</select>

我知道可以使用Page.SelectOptionAsync来设置下拉列表的选中项,但是如何获取当前选中项呢?

当我查看下拉列表的所有属性时,我在ElementHandles中看不到任何区别。


如果只是用于评估/断言,那么期望有值 to_have_value - mfit
4个回答

7
<select id="element_id">
  <option value="1">Option 1</option>
  <option value="2" selected>Option 2</option>
<select>

对于 NodeJS Playwright

从下拉菜单中获取所选选项的 value 值(2):

await page.$eval('#element_id', sel => sel.value)

从下拉列表中获取所选选项的文本(“选项2”):

await page.$eval('#element_id', sel => sel.options[sel.options.selectedIndex].textContent)

对于C#,只需将第二个参数用引号括起来:

await page.EvalOnSelectorAsync<string>("#element_id", "sel => sel.value")
await page.EvalOnSelectorAsync<string>("#element_id", "sel => sel.options[sel.options.selectedIndex].textContent")

太棒了,谢谢。 - giovannipds

5

为了完整起见,这里是我认为更好的NodeJS Playwright选项,使用定位器评估函数

  test('should render correctly', async () => {
    // act
    await page.goto('http://localhost:' + localPort);

    // assert
    async function extractSelectedDisplayedValue(selectedOption) {
      return selectedOption.evaluate(sel => sel.options[sel.options.selectedIndex].textContent);
    }
    const selectedImageOption = page.locator('#imageSelect');
    expect(await extractSelectedDisplayedValue(selectedImageOption)).toBe('Option 1 ');
  }, 60_000)

我知道这个问题是关于C#的,但是当你在整体上搜索该问题时,它会出现,并且我的NodeJs尝试将我带到了这里。


3
谢谢,这真的帮了我很多!对于使用TypeScript的人来说,此示例中的“sel”应该是类型为“HTMLSelectElement”的。 - makeiteasy
1
所以,在https://github.com/microsoft/playwright/discussions/12804的帮助下,`const select = this.page.locator('#UserAddress_State');const testContent = await select.evaluate((node: HTMLSelectElement) => node.options[node.options.selectedIndex].textContent);` - Brian Hong

2
您可以使用EvalOnSelectorAsync,传递一个CSS选择器和一个期望该元素并返回该元素值的函数:
await page.EvalOnSelectorAsync<string>("#txtType", "el => el.value")

-1
看起来答案需要属性"selected"。如果没有"selected"属性会怎么样呢?
<select id="element_id">
  <option value="1">Option 1</option>
  <option value="2" selected>Option 2</option>
<select>

这并没有回答问题。一旦你有足够的声望,你就可以评论任何帖子;相反,提供不需要提问者澄清的答案。- 来自审查 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接