簡體   English   中英

如何通過Selenium和C#從子節點獲取屬性

[英]How to get attribute from child node through Selenium and C#

下面提到的是網頁中的一個節點,目標是在屬性“ onclick”內獲取數據。 我知道我可以使用GetAttribute("onclick")來獲取數據。

但是出於某種原因,我只能找到該輸入節點所在的td。 有人可以告訴是否有一種方法可以從父“ td”節點獲取子“輸入”節點的屬性數據“ onclick”。

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

如果使用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");

希望這些代碼可以解決您的問題。

所需元素是動態元素,因此要獲取屬性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"); 

注意 :這里假設<td>節點在HTML DOM中是唯一的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM