<div id="targetSummaryCount" class="large-text" data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$target_key_30.1.1.0">
<span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$target_key_30.1.1.0.0">0</span>
<span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$target_key_30.1.1.0.1">/</span>
<span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$target_key_30.1.1.0.2">20</span>
</div>
我想使用div id'targetSummaryCount'从上面的html中获取'0'和'20'值。有没有办法在不使用xpath的情况下在Selenium C#中执行此操作?
答案 0 :(得分:1)
您可以使用CSS选择器:
driver.FindElements(By.CssSelector("#targetSummaryCount > span"))
这会将元素下的所有span
元素与id="targetSummaryCount"
匹配。
答案 1 :(得分:1)
我已经用Java发布了解决方案。请将其转换为C#
WebElement divSummary = driver.findElementById("targetSummaryCount");
List<WebElement> targetKeys = divSummary.findElements(By.tagName("span"));
// For getting first and last element
targetKeys.get(0);
targetKeys.get(targetKeys.size()-1);
// For maintaining queue of elements with text 0 or 20
HashMap <Integer, List<WebElement>> elementmap = new HashMap <Integer, List<WebElement>>();
List<WebElement> webElements1 = new ArrayList<WebElement>();
List<WebElement> webElements2 = new ArrayList<WebElement>();
for (WebElement elem : targetKeys){
if(elem.getText().trim().equals("0")){
webElements1.add(elem);
}
else if (elem.getText().trim().equals("20")){
webElements2.add(elem);
}
}
elementmap.put(0,webElements1);
elementmap.put(20,webElements1);
// elementmap.get(0) contains all span tag under target Summary Count div tag
// elementmap.get(20) contains all span tag under target Summary Count div tag
答案 2 :(得分:0)
使用XPath获取“0”和“20”:
string value_00 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[1]").Text;
string value_20 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[3]").Text;
// or
var elements = driver.FindElementsByXPath("//div[@id='targetSummaryCount']/span");
string value_00 = elements[0].Text;
string value_01 = elements[2].Text;
使用Css选择器:
string value_00 = driver.FindElementByCssSelector("#targetSummaryCount > span:nth-child(1)").Text;
string value_20 = driver.FindElementByCssSelector("#targetSummaryCount > span:nth-child(3)").Text;
// or
var elements = driver.FindElementsByCssSelector("#targetSummaryCount > span:nth-child(odd)");
string value_00 = elements[0].Text;
string value_01 = elements[1].Text;
答案 3 :(得分:0)
你可以试试这个。
var spanCount = driver.FindElements(By.XPath("//*[@id='targetSummaryCount']/span")).Count;
var myResult = "";
for (int spanIndex = 0; spanIndex < spanCount; spanIndex++)
{
var spanText = driver.FindElement(By.XPath("//*[@id='targetSummaryCount']/span[" + spanIndex + "]")).Text;
if (spanText != "/")
{
myResult += "span:" + spanIndex + " spanText:" + myResult;
}
}
答案 4 :(得分:0)
你可以试试这个。获取标识为targetSummaryCount
且文字为0
或20
的div子项的范围。
var span_00 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[text()='0']");
var span_20 = driver.FindElementByXPath("//div[@id='targetSummaryCount']/span[text()='20']");