2012-04-19 40 views
3

我正在尝试为我的网站进行测试。在某些用户表单上遇到麻烦。诀窍是,表单中文本字段的数量取决于用户选项(禁用的代码存在于代码中,但具有样式< displayed: none;> tag),所以我试图找到比定位每个元素更灵活的方法元素一个接一个,用try/except块填充表单。需要可见元素的xpath定位器

我使用XPath定位

text_fields = driver.find_elements_by_xpath("//div[@class='form-line']/div[@class='form-inputs']/input[@type='text' and not(ancestor::div[@style='display: none;'])]")

麻烦的是,萤火虫只查找需要的元素,但是当我使用它在我的硒脚本,打印的text_fields名单给我的所有元素,即使没有< displayed: none;>标签

如何获取仅可见元素?

PS对不起,我的英文不好^ _^

+0

def make_an_order(driver): text_fields = driver.find_elements_by_xpath(“// div [@ class ='form-line']/div [@ class ='form-inputs']/input [@ type ='text “) 用于text_fields字段: 尝试: field.clear() 除外: 通 实测值的溶液中。但问题仍然很有趣 – 2012-04-19 11:15:25

+0

注入jQuery并使用[':visible'](http://api.jquery.com/visible-selector/)选择器替代? – Alp 2012-04-19 11:23:09

回答

4

您可以通过常规方式获取所有表单元素,然后遍历列表并删除那些在is_displayed()上不返回true的元素。

+0

谢谢,您的方法工作得很好! – 2012-07-07 08:01:37

1

尝试方法:

text_fields = driver.find_elements_by_xpath(
    "//div[@class='form-line']/div[@class='form-inputs']/input[@type='text' and 
    not(ancestor::div[contains(@style, 'display: none;')])]") 

最重要的部分是:

div[contains(@style, 'display: none;')] 

注意,如果样式包含字符串display:none;display:none,选择器将不匹配。

+0

我忘了提,但我首先尝试了_contains()_方法。同样的故事 – 2012-04-19 11:14:34

+0

请发布您的HTML – Alp 2012-04-19 11:24:06

0

我使用以下,它工作得很好。

self.assertTrue(driver.find_element_by_xpath("//div[@id='game_icons']/div/div[2]/div/a/img")) 

这是用于Selenium和Python的。