2017-03-03 67 views
0

如何從中獲取MY_TROUBLE_TWO並單擊?如何獲得div標記的值

我已經嘗試了下面提到的代碼,但它沒有爲我工作。

試過碼1)

WebElement element = driver.findElement(By.xpath(".//div[7]/div/div/div/div/div/div/div[2]/div[@class='dx-item-content dx-list-item-content']")); 
element.click(); 

試過代碼2)

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//div[7]/div/div/div/div/div/div/div[2]/div[@class='dx-item-content dx-list-item-content']"))).click(); 

試過代碼3)

Select select = new Select(driver.findElement(By.xpath(".//xpath_to_item"))); 
select.selectByVisibleText("MY_TROUBLE_TWO"); 

html代碼如下:

<div class="dx-scrollview-content" onclick="void(0)"> 
    <div id="50d24777-593c-7626-d924-2a3db0e72e89" class="dx-item dx-list-item dx-list-item-selected dx-state-focused" role="option" aria-selected="true" style=""> 
    <div class="dx-item-content dx-list-item-content">MY_TROUBLE_ONE</div> 
    </div> 
    <div class="dx-item dx-list-item" role="option" aria-selected="false"> 
    <div class="dx-item-content dx-list-item-content">MY_TROUBLE_TWO</div> 
    </div> 
</div> 
+1

什麼不起作用?你有錯誤信息嗎?它超時嗎?它無法找到元素? – n247s

回答

1

試試這個下面的代碼來獲取MY_TROUBLE_TWO

注值:而不是使用absolute xpath的,使用relative xpath

說明:在去元素前先放一些等待,等我用了explicit wait的方法。等待查找元素使用text方法用div標籤獲取元素。

WebDriverWait wait = new WebDriverWait(driver, 15); 
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//div[contains(text(), 'MY_TROUBLE_TWO')]")))).click(); 
+0

謝謝。你的決定對我來說很有用! – Sergey

+0

不要使用'Thread.sleep()'。相反,使用WebDriverWait並等待元素可點擊等。 – JeffC

+1

@JeffC,我使用WebDriverWait是這樣的: 'WebDriverWait wait = new WebDriverWait(driver,10); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(「// div [contains(text(),'SOME_TEXT')]」)))。click();' – Sergey