我在搜索innerHTML元素时遇到了一些麻烦。 编辑:(我的意思是从innerHTML中搜索元素。)
目标:查找变量内部的ID
我的英语不好,我希望大家都明白。
//All css elements
var itemHolder = WebDriver.FindElementsByClassName("itemHolder");
//Get singleElement from itemHolder
foreach (var element in itemHolder)
{
//i think that easy to understand
if (!element.GetAttribute("style").Equals("display: none;"))
{
var innerHtml = element.GetAttribute("innerHTML");
//simply regex for find the right one element
string reg = @"(item app730 context2)";
bool command = Regex.IsMatch(innerHtml, reg, RegexOptions.IgnoreCase);
if (command)
{
Console.WriteLine(element.GetAttribute("innerHTML"));
var inner = element.GetAttribute("innerHTML");
//inner = <div style='border - color: rgb(210, 210, 210); z - index: 3; position: relative; ' class='item app730 context2' id='item730_2_3294048593'></div>
//now i need id from inner, how can i do it?
//first variant: Regex inner, found item730_2_3294048593, that is a hard way i find. im bad in regex
//Regex Example: strike = Regex.Match(inner, "(id=')[a-zA-Z_0-9]{20}").ToString();
//second and i think bether variant but do not have a plan how to start: P
// 1. convert inner to html elements
// 2. search id
//var found = Regex.Match(inner, "");
break;
}
}
}
我希望有人可以帮助我,非常感谢! 问候Ivorysmoker
答案 0 :(得分:1)
我假设您有这样的HTML布局:
<div id="outer">
<div id="inner">
hello
</div>
</div>
如果是这种情况,您可以使用IWebElement
的{{1}}方法查找子元素:
FindElement
请注意,XPath for inner在开头有一个句点,表示任何结果必须是我们搜索的元素的子元素。
从那里你可以IWebElement outer = FindElement(By.XPath("//*[@id='outer']"));
IWebElement inner = outer.FindElement(By.XPath("./div"));
来获取你的身份。
答案 1 :(得分:0)
扩展Ben Chand的答案。请原谅这个伪代码:
IWebElement outer = By.XPath("//*[@class='itemHolder']");
....
public By getInnerByIndex(int index) {
By inner = By.XPath(".//div[@id='innerHtml'][" + index + "]");
By innerLocator = new ByChained(outer, inner);
return innerLocator;
}
答案 2 :(得分:0)
我从innerHTML获取ID的方法。 (动态内容)
var strike = Regex.Match(inner, "(id=')[a-zA-Z_0-9]{20}");
result = strike.ToString().Replace("id='", "");
Regex Out:id ='item730_2_3294048593 Regex Out替换:item730_2_3294048593
感谢所有答案!
问候Ivorysmoker