我有一个非常复杂的网站,我正在尝试用Selenium进行测试。但是当我尝试获取XPath时,我得到了如下示例
//*[@id="datatable1595356931082"]/div[1]/div[2]/table/tbody/tr[3]/td[2]/div/select/option[8]
绝对XPath:
/html/body/div[4]/div[2]/div[2]/div/div[2]/div[2]/div/div/div[1]/div[2]/table/tbody/tr[3]/td[2]/div/select/option[8]
在Selenium中,我尝试使用绝对路径
driver.find_element_by_xpath("/html/body/div[4]/div[2]/div[2]/div/div[2]/div[2]/div/div/div[1]/div[2]/")
它试图出错,说找不到XPath。datatable似乎在运行时创建了一个动态数字。 这里我要做的是选择一个下拉列表,如下所示
<div role="columnheader" class="webix_hcell webix_ss_filter">
<select>
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
.
.
.
</select>
</div>
我也试过了
driver.find_element_by_class_name('webix_hcell webix_ss_filter')
但这也是错误的
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".webix_hcell webix_ss_filter"}
对于上面的一个
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression /html/body/div[4]/div[2]/div[2]/div/div[2]/div[2]/div/div/div[1]/div[2]/ because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '/html/body/div[4]/div[2]/div[2]/div/div[2]/div[2]/div/div/div[1]/div[2]/' is not a valid XPath expression.
(Session info: chrome=84.0.4147.89)
从第一次尝试开始,WebElement将显示为动态元素,这是由于存在id属性值作为
datatable1595356931082
,该属性值可能会在每次访问时或定期更改:在第二次尝试中,您使用了绝对xpath。由于网站是动态的,元素将在每次访问或定期访问时重新定位:
在第三次尝试中,xpath以
/
结尾,这是不需要的。因此你面对InvalidSelectorException在第四次尝试中,您通过
driver.find_element_by_class_name('webix_hcell webix_ss_filter')
传递了多个类,其中asdriver.find_element_by_class_name()
只接受一个类名作为参数Select
类李>解决方案
相关的基于文本的HTML将帮助我们构建一个规范的答案。但是,根据提供的HTML,单击文本为A的选项,您可以使用以下任意一种Locator Strategies:
使用
XPATH
和select_by_visible_text()
:使用
CSS_SELECTOR
和select_by_value()
:注意:您必须添加以下导入:
这不起作用,因为
*_by_class_name
仅用于单个类名:尝试使用
*_by_css_selector
:相关问题 更多 >
编程相关推荐