2017-04-22 1 views
0

私はショッピングサイトからのアイテムのリストを持っています。いくつかのアイテムはスパンスタイル= ".."を持ち、スタイルのないものもいくつかあります。スタイル= "font-size:11px ...なのでスパンだけのテキスト値が必要です。この場合は30ドルと60ドルです。GetElementsはパラレントスパンからのみ

次のコード
<span class="item_price"> <span style="font-size:11px;color:#d00;text-decoration:line-through">50 USD</span>&nbsp;&nbsp;&nbsp;&nbsp; 
30 USD </span>      
</div> 
<span class="item_price"> 
60 USD</span> 

は、同じクラスからからすべてのテキスト値を返します。

IList<IWebElement> prices = driver.FindElements((By.ClassName("item_price"))); 

     foreach (var correctPrice in prices) 
     { 
      { Console.Write(correctPrice.Text); } 

答えて

1

styleのSPANはspan.item_priceの内部にあるので、外側のSPANには.Textを入力すると、内部のSPANのテキストも取得されます。 span.item_priceを取得して、含まれているすべての要素をループし、元の文字列から.Textを削除することができます。その後、

static string RemoveChildText(IWebElement parent) 
{ 
    string text = parent.Text; 
    foreach (IWebElement e in parent.FindElements(By.CssSelector("*"))) 
    { 
     text = text.Replace(e.Text, ""); 
    } 

    return text.Trim(); 
} 

と私はあなたが投稿、それはこれが提供するHTML与えられた動作しません

30 USD 
60 USD 
+0

これは問題 –

0

あなたは、XPath、この

IList<IWebElement> prices = driver.FindElements(By.Xpath("//span[@class='item_price' and not(span[contains(@style,'font-size')])]")); 

     foreach (var correctPrice in prices) 
     { 
      { Console.Write(correctPrice.Text); } 

この手段のようなものを使用して、あなたは子供なしでスパンを探していることを達成できますいくつかの基準でスパンa

+0

を返されたHTMLでこれをテストした

IReadOnlyCollection<IWebElement> prices = Driver.FindElements(By.CssSelector("span.item_price")); Console.WriteLine(RemoveChildText(prices.ElementAt(0))); Console.WriteLine(RemoveChildText(prices.ElementAt(1))); 

のようにそれを呼び出します。私の答えを参照してください... – JeffC

+0

はい、正しい、提供されたhtmlを見直して、私は簡単にhtmlを参照してクラスitem_priceと3つのスパンがあると思った –

関連する問題