2014-04-15 84 views
15

我試圖使用XPath來查找包含一段文字的元素,但我不能讓它的工作定位鏈接....硒和XPath - 含有文本

WebElement searchItemByText = driver.findElement(By.xpath("//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text()='Some text')]")); 

如果我用「包含」事件刪除最後一位,它會找到我的span元素,但我需要根據文本內容選擇它。它不會與「某些文本」完美匹配,因爲它也可能包含截斷的字符串。

任何人都看到這個問題?

+0

您應該顯示'a'元素(及其周圍元素)的HTML,以便我們可以將它的結構與您的XPath遵循的內容進行比較。 – Arran

回答

29

我認爲這個問題是在這裏:

[contains(text()='Some text')] 

爲了打破這種下來,

  1. []是一個條件,它在 中的每個單獨節點上運行,即節點集 - 您的案例中的每個跨度節點。它匹配任何單獨的節點,它操作 匹配括號內的條件。
  2. text()是一個選擇器 ,它與上下文的子節點的所有文本節點相匹配 節點 - 它返回一個節點集。
  3. contains是對字符串操作 的函數。如果它通過一個節點集,節點集是converted into a string by returning the string-value of the node in the node-set that is first in document order

你應該嘗試改變這

[text()[contains(.,'Some text')]]

  1. []是有條件的,在該節點的每個單獨節點 上操作設置text()是匹配所有的選擇文本 節點是上下文節點的子節點 - 它返回一個節點 集合。

  2. 內部[]是在該節點集中的每個節點上運行的條件。

  3. contains是一個對字符串進行操作的函數。這裏通過 個別文本節點(.)。

+1

真棒解釋! –

+0

話題略有變化,這也能爲班上班嗎? ''[contains(class()='Some class')]''' – TangibleDream

10

使用此

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')] 

OR

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')] 
+0

謝謝!去了第一個:) – joakimnorberg

-4
@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount; 

這種方法會爲你工作,希望。

+1

請在答案中加入更多信息。 –

2
@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton; 

public void clickOnSubmitButton() { 
    submitButton.click(); 
}