c#
  • selenium
  • xpath
  • webdriver
  • css-selectors
  • 2014-07-15 87 views 2 likes 
    2

    在Visual Studio中編寫Selenium WebDriver的代碼時,同一按鈕的這兩個代碼只能正常工作一次。單擊具有相同CssSelector或相同XPath的所有元素FindElements

    點擊按鈕通過CSS選擇器:

    driver.FindElement(By.CssSelector(".follow-text")).Click(); 
    

    點擊按鈕與XPath:

    driver.FindElement(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")).Click(); 
    

    直到這個正確的...


    但我想點擊所有按鈕不只是第一個,並且由於FindElements(複數)讓我錯誤,我怎麼能點擊所有按鈕與相同的代碼?

    使用此得到錯誤:

    List<IWebElement> textfields = new List<IWebElement>(); 
    driver.FindElement(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")).Click(); 
    driver.FindElement(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn'][3]")).Click(); 
    

    見捕獲:

    enter image description here

    回答

    1

    您需要遍歷FindElements結果,並在每個項目上調用.Click()

    var result = driver.FindElements(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")); 
    foreach (IWebElement element in result) 
    { 
        element.Click(); 
    } 
    

    僅供參考,您需要將XPath括在括號內以使您使用XPath索引的嘗試代碼工作:

    driver.FindElement(By.XPath("(//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn'])[3]")).Click(); 
    
    +0

    我在嘗試,然後我現在鏈接一個捕獲,謝謝 – Lion6

    0
    List <WebElement> list = driver.FindElements(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")); 
    

    然後遍歷列表中包含的元素列表:

    int x = 0; 
    while (x < list.size()) { 
        WebElement element = list.get(x); 
        element.click(); 
    } 
    
    +0

    出現此錯誤,請參閱捕獲請:http://postimg.org/image/6jhaj5ncf/ – Lion6

    +0

    我想說感謝您的時間來閱讀和幫助 – Lion6

    0

    您應該使用類似的東西(注意findElements的S)

    List<WebElement> textfields = driver.findElements(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")); 
    

    ,然後用迭代for循環

    for(WebElement elem : textfields){ 
        elem.click(); 
    } 
    
    +0

    嗯...期待的錯誤;請看:http://postimg.org/image/j272r8m9p/ – Lion6

    +0

    編輯,只是遺忘了(); – singe3

    +0

    出現此錯誤,我做什麼壞..? mm aix:http://s22.postimg.org/d38bhviyp/QUINTO.jpg謝謝 – Lion6

    相關問題