使用Xpath单击页面上的所有元素会导致ElementNotVisibleException

时间:2013-03-01 11:14:46

标签: python selenium

我有一个帮助函数来查看页面并打开它找到的每个帮助按钮。这很好,很简单;

def openHelp(ff):
    """
    Opens all the help buttons on the screen
    @type ff: instance of webdriver
    @param ff: firefox instance of webdriver
    """
    allHelpButtons = ff.find_elements_by_xpath('//a[@class="helpButton"]')
    for helpButton in allHelpButtons:
        helpButton.click()

然而,在某些页面上,可能会通过javascript隐藏帮助按钮及其对应的字段,这似乎是Selenium尝试点击这些隐藏按钮时导致ElementNotVisibileException的原因。

每个帮助按钮在标记中显示相同,没有应用display:none因此我无法检查。它们就是这样;

<a class="helpButton" title="Help about: Field" href="#">
    <img alt="Help about: Field" src="/static/images/helpIcon.png">
</a>

如果存在此异常,我假设必须有一个方法可用于检查元素是否可见。理想情况下,我只想收集我allHelpButtons列表中的所有可见元素,但我找不到任何关于此的文档。 我可以使用xpath搜索执行检查,还是在收集元素后必须检查它们?

奖金问题

我还想知道,如果你可以通过匹配名称和值来选择列表项。例如,我在页面中将“是/否”单选按钮选项定义为ul;

<ul class="compact horizontal ">
    <li>
        <input id="id_fieldname_0_true" type="radio" value="True" name="fieldname">
        <label for="id_fieldname_0_true">Yes</label>
    </li>
    <li>
        <input id="id_fieldname_0_false" type="radio" value="False" name="fieldname">
        <label for="id_fieldname_0_false">No</label>
    </li>
</ul>

显然id是唯一的,但我宁愿能够使用选择器来挑选'name'和'value',因为我认为这样可以更容易地制作我可以传递值的泛型选择器

1 个答案:

答案 0 :(得分:1)

有一个is_displayed功能。

检查以下源代码,第162行:

https://code.google.com/p/selenium/source/browse/py/selenium/webdriver/remote/webelement.py

至于你的奖金问题,这也是由XPath完成的,点击Yes按钮收音机:

//label[text()='Yes']/preceding-sibling::input

和No:

//label[text()='No']/preceding-sibling::input