【问题标题】:Need xpath locators for visible elements需要可见元素的 xpath 定位器
【发布时间】:2012-04-19 10:45:13
【问题描述】:

我正在尝试对我的网站进行测试。在某些用户表单上遇到问题。诀窍是,表单中文本字段的数量因用户选项而异(代码中存在禁用的字段,但有一个样式 displayed: none;> 标记),所以我试图找到比逐个定位每个元素并使用 try/except 块填充表单。

我正在使用 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;'])]")

问题是萤火虫只定位需要的元素,但是当我使用它时,我的 selenium 脚本,打印text_fields 的列表会给我所有的元素,即使没有 displayed: none;> 标签

我怎样才能只获得可见元素?

PS 对不起我的英语不好^_^

【问题讨论】:

  • def make_an_order(driver): text_fields = driver.find_elements_by_xpath("//div[@class='form-line']/div[@class='form-inputs']/input[@ type='text") for field in text_fields: try: field.clear() except: pass 找到了解决方案。但是这个问题还是很有趣的
  • 正在注入 jQuery 并使用 :visible 选择器作为替代方案?

标签: python xpath selenium webdriver selenium-webdriver


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试contains() 方法:

    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,则选择器将不匹配。

    【讨论】:

    • 我忘了提,但我先尝试了 contains() 方法。同样的故事
    【解决方案3】:

    我使用以下,效果很好。

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

    这当然适用于 Selenium 和 Python。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-09
      • 2016-10-21
      • 2018-10-23
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      相关资源
      最近更新 更多