2017-11-10 80 views
-1

在foreach循環中,我捕捉元素的一段文本(如果顯示的話)。不過,我只想抓取元素文本中的數字(包括正數和負數)。如何從硒文本中獲取數字?

目前的文本可以讀取:

+156 on same day 
or 
-88 on same day 

我只想抓住從這段文字的值,所以這應該要麼是:

156 
or 
-88 

我怎樣才能抓住唯一的數字,如果減去alternativeAirportPrice.Text中的負號?

public string GetAlternativeAirportPrice(By airportPriceLocator) 
{ 
    var alternativeAirportPrices = _driver.FindElements(airportPriceLocator); 

    foreach (var alternativeAirportPrice in alternativeAirportPrices) 
    { 
     if (alternativeAirportPrice.Displayed) 
      return alternativeAirportPrice.Text; 
    } 
    return null; 
} 
+0

有很多方法可以做到這一點..但你可以使用一些內置的擴展方法,如'Char.IsNumeric'在網上做一個快速的谷歌搜索示例 – MethodMan

+0

這不是一個硒問題因爲它是一個字符串解析問題。尋找這可能有助於你的研究。 – mrfreester

+1

[Regex for numbers only]可能的重複(https://stackoverflow.com/questions/273141/regex-for-numbers-only) –

回答

0

嘗試代碼:

string test = "-123"; 
string result; 
foreach(Char i in test) { 
    if (Char.IsNumber(i)) { 
     result += i; 
    } 
} 
int value = int.Parse(result); 
0

,如果你需要數以int,而不是你行:

return alternativeAirportPrice.Text; 

你可以寫:

int r; 
    int.TryParse(alternativeAirportPrice.Text.Trim().Split(' ').First(), out r); 
    return r; 

它將工作對於你寫的兩種情況。如果可能有空字符串,則可以在調用字符串方法之前檢查空字符串。如果你可能有十進制數 - 只需將int改爲double即可。 但是,你必須改變你的方法返回類型爲int。