Playwright 中点击元素的最安全方式是什么?

huangapple go评论137阅读模式
英文:

What is the safest way to click on an element in Playwright?

问题

我需要使用Playwright for Python点击一个对象!有时元素的CSS会发生变化,或者它没有ID。我通常使用page.click(XPATH),但我知道还有很多其他方法,比如:

1 - page.get_by_text("Get Started").click()
2 - page.get_by_role("button", name="Submit").click()
3 - page.get_by_selector("#login-button").click()
4 - page.get_by_selector("//div[@class='user-agent']").click()
5 - locator = page.locator(".user-agent") locator.click()

哪种方法成功的可能性最高?

英文:

I need to click on an object using Playwright for Python! Sometimes the element's CSS changes, or it doesn't have an ID. I usually use
page.click(XPATH), But I know there are many other ways like:

1 - page.get_by_text("Get Started").click()
2 - page.get_by_role("button", name="Submit").click()
3 - page.get_by_selector("#login-button").click()
4 - page.get_by_selector("//div[@class='user-agent']").click()
5 - locator = page.locator(".user-agent")
    locator.click()

Which has the highest probability of success?

答案1

得分: 1

Playwright提供了一些建议:https://playwright.dev/docs/best-practices#best-practices(这些建议适用于Node.js文档,但在Python中的信息相同)。就个人而言,我同意这些建议:编写基于用户可见内容的测试(使用get_by_text、get_by_role),依赖于css/xpath等内容的测试更容易出现不稳定性。

英文:

Playwright has written som good advices: https://playwright.dev/docs/best-practices#best-practices (they are in the node.js docs, but the message is the same with Python). Personally, I agree with them: Write test based on whats visible to the user (get_by_text, get_by_role), tests depending on css/xpath etc. is more prone to flakiness.

答案2

得分: 0

如果ID不可用,我倾向于选择第二个选项,因为它具备以下特点:

  1. 独特:通常页面上只有一个提交按钮。

  2. 组合:两个属性不太可能同时更改。

我认为一个定位器中最理想的特点是 - 同时具备刚性和灵活性,而第二个选项具备这一特点。

英文:

If Id is not available, I would tend to favor second option as its:

  1. Unique : Usually there is only one submit button on a page.

  2. combination: Two properties are less likely to change at the same time.

I think the most desirable quality in a locator is - rigid and flexible at the same time, which second option has it.

huangapple
  • 本文由 发表于 2023年7月7日 04:43:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定