如何为 PrimeFaces 编写 Python selenium 测试?
How can I write Python selenium test for PrimeFaces?
我正在尝试编写一个 Selenium 测试,但问题是我了解到该页面是使用 PrimeFaces 生成的,因此元素 ID 会不时随机更改。不使用 ID 不是很可靠。有什么我可以做的吗?
没有有意义的稳定 ID 不是问题,因为总有其他方法可以在页面上定位元素。仅举几个选项:
部分 id 与 XPath 或 CSS 匹配,例如:
# contains
driver.find_element_by_css_selector("span[id*=customer]")
driver.find_element_by_xpath("//span[contains(@id, 'customer')]")
# starts with
driver.find_element_by_css_selector("span[id^=customer]")
driver.find_element_by_xpath("//span[starts-with(@id, 'customer')]")
# ends with
driver.find_element_by_css_selector("span[id$=customer]")
类 其中 refer/tell 一些关于数据类型 ("data-oriented locators") 的有价值的信息:
driver.find_element_by_css_selector(".price")
driver.find_element_by_class_name("price")
从标签侧身:
# <label>Price</label><span id="65123safg12">10.00</span>
driver.find_element_by_xpath("//label[.='Price']/following-sibling::span")
links by link 文字或部分 link 文字:
driver.find_element_by_link_text("Information")
driver.find_element_by_partial_link_text("more")
而且,您当然可以发挥创意并将它们结合起来。还有更多:
还有这个相关的主题讨论了选择在页面上定位元素的方法时的最佳实践:
我正在尝试编写一个 Selenium 测试,但问题是我了解到该页面是使用 PrimeFaces 生成的,因此元素 ID 会不时随机更改。不使用 ID 不是很可靠。有什么我可以做的吗?
没有有意义的稳定 ID 不是问题,因为总有其他方法可以在页面上定位元素。仅举几个选项:
部分 id 与 XPath 或 CSS 匹配,例如:
# contains driver.find_element_by_css_selector("span[id*=customer]") driver.find_element_by_xpath("//span[contains(@id, 'customer')]") # starts with driver.find_element_by_css_selector("span[id^=customer]") driver.find_element_by_xpath("//span[starts-with(@id, 'customer')]") # ends with driver.find_element_by_css_selector("span[id$=customer]")
类 其中 refer/tell 一些关于数据类型 ("data-oriented locators") 的有价值的信息:
driver.find_element_by_css_selector(".price") driver.find_element_by_class_name("price")
从标签侧身:
# <label>Price</label><span id="65123safg12">10.00</span> driver.find_element_by_xpath("//label[.='Price']/following-sibling::span")
links by link 文字或部分 link 文字:
driver.find_element_by_link_text("Information") driver.find_element_by_partial_link_text("more")
而且,您当然可以发挥创意并将它们结合起来。还有更多:
还有这个相关的主题讨论了选择在页面上定位元素的方法时的最佳实践: