问题描述
我正在尝试获取页面上的iFrame列表,但是由于某些原因,我一直遇到两个错误。即,当执行var iFrame = driver.FindElements(By.TagName("frame"));
时,会得到空驱动程序和“对象引用未设置为对象的实例”。我花了半天的时间来解决这个问题,除非我在Stack Overflow上寻求帮助,否则我会陷入困境。
BaseiFrame类:
public class BaseIFrame
{
protected IWebDriver _driver;
private ReadOnlyCollection<IWebElement> _elements;
private ReadOnlyCollection<IWebElement> _iframes;
public BaseIFrame(IWebDriver _driver)
{
this._driver = _driver;
_iframes = _driver.FindElements(By.TagName("frame"));
_elements = new ReadOnlyCollection<IWebElement>(_iframes);
}
public void GetAlliFrames()
{
try
{
if (_elements.Count > 0)
{
_driver.SwitchTo().Frame(0);
}
}
catch (Exception e)
{
Debug.WriteLine(e.FormatExceptionMessage(this));
throw;
}
}
}
调用BaseiFrame类的BaseiFrameTests类方法
public class BaseiFrameTests : SharedBase
{
protected IWebDriver _driver;
private BaseConfig config;
private BaseConfig initialUrl;
//string url = "http://127.0.0.1:1024/";
public BaseiFrameTests()
{
}
public override BaseConfig getConfig()
{
return new Config
{
initialUrl = "http://the-internet.herokuapp.com/nested_frames"
};
}
public override BaseConfig loadConfig()
{
return new BaseConfig();
}
public override IWebDriver getDriver()
{
return instantiateWebDriver("edge");
}
[TestMethod]
public void AssertiFrameLength()
{
BaseIFrame bif = new BaseIFrame(_driver);
bif.GetAlliFrames();
}
}
解决方法
更新:我可以通过在getDriver()
方法中将new BaseiFrame();
初始化为AssertiFrameLength
来解决问题。