2017-03-08 64 views
0

我試圖使用Eclipse中的Selenium提交按鈕自動化工作流。檢查字符串的外觀(並提取)數字值

我使用的是自定義函數waitForVisible檢查,如果WebElement ID爲「naviInfo」顯示,如果它擁有具有或者「沒有行被發現」或消息「未找到{number}行」的消息。

問題是我無法排序和檢查文本的數字部分。下面給出了示例代碼。

String message = waitForVisible(By.id("naviInfo")).getText(); 

if ("No rows were found".equals(message)) { 
     log.info("No rows were found after submit"); 
} 
else if ("**1804** rows were found".equals(message)) { 
     log.info("**1804** rows found after submit"); 
} 
else { 
     (other error checks) 
} 

我該如何檢查在找到普通文本行之前是否有數字值?另外還將這個數字保存到一個變量?

回答

1

如果我找到你了,你只是問如何驗證消息匹配預期的模式,以及如何從字符串中提取數字?在這種情況下,這與Selenium無關,但是是一個簡單的正則表達式問題。

Pattern p = Pattern.compile("^\\*{2}(\\d+)\\*{2} rows were found$"); //pattern that says: start of string, followed by two *s, then some digits, then two *s again, then the string " rows were found", and finally the end of string, capturing the digits only 
Matcher m = p.matcher("**1804** rows were found");  
boolean found = m.find(); //find and capture the pattern of interest 
if (found) 
    int count = Integer.parseInt(m.group(1)); //get the first (and only) captured group, and parse the integer from it 

閱讀關於Java的正則表達式here

+0

謝謝kaqqao。你的評論確實幫助我弄清楚我需要什麼。 – Nitya

0

所以這就是我讓自己的病情起作用的原因。

if (" no rows were found".equals(waitForVisible(By.id("naviInfo")).getText())) 
    waitForVisible(By.xpath("//td[contains(text(),'Nothing found to display.')]")); 
else if (Pattern.matches("^ \\d+ rows were found$", waitForVisible(By.id("naviInfo")).getText())) 
    waitForVisible(By.xpath("//tbody//tr//td/a")); 
else 
    other error checks