【问题标题】:How to get attribute from child node through Selenium and C#如何通过 Selenium 和 C# 从子节点获取属性
【发布时间】:2018-12-18 12:18:54
【问题描述】:

下面提到的是网页中的一个节点,目的是获取属性“onclick”内的数据。我知道我可以使用GetAttribute("onclick") 来获取数据。

但出于某种原因,我只定位了这个输入节点所在的 td。有人可以告诉是否有办法从父“td”节点获取子“输入”节点的属性数据“onclick”。

 <td align="center">
    <input type="button" class="button" value="View Pdf" onclick="showFilePreView('98374');">
    </td>

【问题讨论】:

    标签: c# selenium-webdriver xpath css-selectors getattribute


    【解决方案1】:

    如果你使用selenium-webdriver,那么你可以先找到父元素,然后使用childElement = parentElemnent.FindElement(By.)找到子元素。

    在你的情况下,你可以试试下面的代码:

    IWebElement parentElement = YourWebDriver.FindElement(By.TagName("td"));
    // those codes above assume that there is only one "td" node in your case.    
    
    IWebElement childElement = parentElement.FindElement(By.Name("button"));
    String theStringYouWant = childElement.GetAttribute("onclick");
    

    希望这些代码可以解决您的问题。

    【讨论】:

      【解决方案2】:

      所需元素是 dynamic 元素,以便获取 onclick 属性的 值,即 showFilePreView('98374') 你必须诱导 WebDriverWait 让元素可见,你可以使用以下任一解决方案:

      • CssSelector:

        new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("td[align='center']>input.button[value='View Pdf']"))).GetAttribute("onclick")
        
      • XPath:

        new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//td[@align='center']/input[@class='button' and @value='View Pdf']"))).GetAttribute("onclick");
        

      注意:这里假设&lt;td&gt; 节点在HTML DOM 中是唯一的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多