如何在C# Selenium中定位元素并提取指定文本1.27?
用C# + Selenium提取目标数值“1.27”的简便方法
第一步:精准定位目标元素
优化原有XPath,只匹配包含“Floor Price:”的元素,避免返回多个结果:
//p[@class='sc-1xf18x6-0 sc-1aqfqq9-0 iUhqVy ghtrzb' and contains(text(), 'Floor Price:')]
第二步:提取“1.27”的两种简便方式
方式一:C#字符串分割处理
先获取元素完整文本,再通过分割、修剪得到目标数值:
// 定位到目标元素 IWebElement floorPriceElement = driver.FindElement(By.XPath("//p[@class='sc-1xf18x6-0 sc-1aqfqq9-0 iUhqVy ghtrzb' and contains(text(), 'Floor Price:')]")); // 提取并处理文本 string floorPriceText = floorPriceElement.Text; string targetValue = floorPriceText.Split(':')[1].Trim(); // 最终得到"1.27"
方式二:XPath内置函数直接提取
利用XPath的substring-after函数,直接在定位阶段获取目标数值,无需额外字符串处理:
// 通过XPath函数直接提取 IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver; string targetValue = jsExecutor.ExecuteScript( "return document.evaluate('//p[@class=\"sc-1xf18x6-0 sc-1aqfqq9-0 iUhqVy ghtrzb\" and contains(text(), \"Floor Price:\")]/substring-after(text(), \"Floor Price: \")', document, null, XPathResult.STRING_TYPE, null).stringValue;" ).ToString();
内容的提问来源于stack exchange,提问作者Asparuh Ivanov
相关产品推荐
相关产品推荐

