html
  • selenium
  • xpath
  • 2017-10-12 183 views -2 likes 
    -2

    假设我想检查使用XPATH的HTML标签旁边是否存在复选框,我该如何去做?如何检查HTML中是否存在另一个元素

    例如:

    <div> 
        <input type="checkbox" /> 
        <label>This Is A Test</label> 
    </div> 
    

    我知道我可以通过使用"//label[.='This Is A Test']"获取标签,我想我会一直能够看到是否存在该复选框使用//label[.='This Is A Test']/parent::div/checkox但(使用Selenium)我得到一个错误该复选框不存在。

    回答

    1

    XPath Axes

    [axisname::nodetest[predicate]] 
    
        @* selects all the attributes of the context node 
        .. selects the parent of the context node 
    

    XML模板:

    <div> 
        <input type="checkbox" /> 
    
        <label>This Is A Test</label> 
    
        <input type="checkbox1" /> 
    </div> 
    

    以下的XPath可以帮助你Check

    //label[.='This Is A Test']/../input[@type="checkbox"] 
    //label[.='This Is A Test']/parent::*/input[@type="checkbox"] 
    //label[.='This Is A Test']/ancestor::div/input[@type="checkbox"] 
    
    False « 
    //label[.='This Is A Test']/../input[@type="check"] = //input[@type="checkbox"] 
    
    True « 
    //label[.='This Is A Test']/../input[@type="checkbox"] = //input[@type="checkbox"] 
    
    //label[.='This Is A Test']/following::input[@type="checkbox1"] = //input[@type="checkbox1"] 
    
    //label[.='This Is A Test']/preceding::input[@type="checkbox"] = //input[@type="checkbox"] 
    
    0

    复选框不是标签的父项。根据你的x路径,它检查父母不是兄弟姐妹。

    检查标签旁边的复选框。你可以尝试下面的x路径。

    //input[@type='checkbox']/following-sibling:label[.='This Is A Test'] 
    

    //label[.='This Is A Test']/preceding-sibling:input[@type='checkbox'] 
    
    0

    基于标签名称,得到的复选框。

    //label[text()='This Is A Test']/preceding-sibling::input[@type='checkbox'] 
    

    说明的XPath: -首先,你必须得到复选框标签名称。因此,使用text()方法使用<label>标记开始您的xpath,然后使用preceding-sibling关键字获取<input>标记以及type属性。

    +0

    @MrThursday,你有没有试过这个答案?我对xpath的解释对你有帮助吗? –

    +0

    如果问题得到解决,请将此答案标记为“已接受”。 :) –

    相关问题