2017-03-17 29 views
3

我有以下HTML代碼的HTML文件:的XPath建議根據需要來選擇文本

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title>page XYZ</title> 
 
</head> 
 

 
<body> 
 
<p><b>bold text</b> some more text </p> 
 
    
 
    <p><b>1.</b>&nbsp;hello<br><b>2.</b>&nbsp;how<br><b>3.</b>&nbsp;do you do?</p><p>some more text in a paragraph.</p> 
 
    </body> 
 
</html>

我需要寫的XPath與他們的文本,即打印3分,

1. hello 
2. how 
3. do you do? 

到目前爲止我試過這個:(但它不是打印文字)

List<WebElement> list = driver.findElements(By.xpath("//p/following-sibling::p/b")); 

    for (int i = 0; i < list.size(); i++) { 

     WebElement el = list.get(i); 
     String text = el.getText(); 
     System.out.println(text); 
} 

請給我建議。

回答

0

要選擇純文本,你應該使用//p[2]/text()
,如果你需要打印1. 2. 3.你應該,如果你需要選擇你都應該使用 //p[2]作爲字符串,不.findElements()然後用p[2]/b

在你的代碼分裂它像一個列表

+1

// P [2]的工作(所以我接受你的答案),但同樣的硒,使用文本()的XPath函數表達式會將錯誤作爲無效選擇器引發。 – dheer

1

使用xpath "(//p[2])/text()"這將返回兄弟<p>標記內的文本。使用xpath "(//p[2])/b"以粗體讀取數字1,2,3。

爲了得到所需的輸出,你可以嘗試以下方法:

List<WebElement> numberList = driver.findElements(By.xpath("(//p[2])/b")); 
List<WebElement> textList = driver.findElements(By.xpath("(//p[2])/text()")); 

for(int i = 0; i < textList.size() && i < numberList.size(); i++) { 
    System.out.println(numberList.get(i).getText() + " " + textList.get(i).getText()); 
} 
+0

感謝您的回覆。 XPath表達式「(// p [2])/ text()」僅適用於XPath,但在Selenium中,它將引發錯誤:InvalidSelectorError。 – dheer