硒点击几个链接一个接一个

本文关键字:一个 链接 几个 | 更新日期: 2023-09-27 18:26:39

我在一个网页上有一个表,上面有很多值重复如下:

Description     App Name    Information
Some Desc1       App1         Some Info
Some Desc2       App2         Some Info
Some Desc3       App2         Some Info
Some Desc4       App3         Some Info
Some Desc5       App4         Some Info

在我的应用程序启动时,它会要求用户输入自己选择的应用程序名称。我想要的是,如果我选择APP2,它应该首先选择"Some Desc2",这将导致另一个页面,在那里我会做一些事情。然后它应该再次回到上一页,这次它应该选择"Some Desc3",这将导致另一页。此操作应重复n次,直到selenium找不到指定的appname为止。

我尝试了如下所示:

//Finding Table, its rows and coloumns
int rowcount = driver.FindElements(By.Id("someid")).Count;
for (int i = 0; i < rowcount; i++)
{
//Finding App name based on user entered text
  var elems = driver.FindElements(By.PartialLinkText(text));
  IList<IWebElement> list = elems;
  for (int j = 0; j < list.Count; j++)
  {
    var table = driver.FindElement(By.Id("someid"));
    IList<IWebElement> rows = table.FindElements(By.TagName("tr"));
    IList<IWebElement> cells = rows[i].FindElements(By.TagName("td"));
    //Again finding element based on user entered text
    var elem = driver.FindElements(By.PartialLinkText(text));
    list = elem;
    if (list[1].Text.Equals(text))
    {
      list[0].Click();
      string duration;
      string price;
      var elements = driver.FindElements(By.Id("SPFieldNumber"));
      IList<IWebElement> lists = elements;
      duration = lists.First().Text.ToString();
      price = lists.ElementAt(1).Text.ToString();
      MessageBox.Show(duration);
      MessageBox.Show(price);
      driver.Navigate().Back();
    }
 }

}

运行此代码会正确选择"Some Desc2",一切都很顺利。但在返回到上一页后,c#抛出一个异常"缓存中找不到元素——也许该页在查找selenium后发生了更改"。

硒点击几个链接一个接一个

对于这个特定的问题,您在循环之前找到tablerow元素,然后通过在循环内部调用driver.Navigate().Back();,您的tablerow不再在DOM中(因为页面更改,DOM更改,表元素不再是您在循环外找到的元素)

试着把它们放在循环中

int rowCount = driver.FindElements(By.CssSelector("#table_id tr")).Count; // replace table_id with the id of your table
for (int i = 0; i < rowCount ; i++)
{
    var table = driver.FindElement(By.Id("some ID"));
    rows = table.FindElements(By.TagName("tr"));
    // the rest of the code
}

然而,除了解决您的问题外,我真的建议您先阅读Selenium文档并学习一些基本的C#编程,这将节省您在这里提问的大量时间。

  • 你为什么每次都这么做
var elems = driver.FindElements(By.PartialLinkText(text));
IList<IWebElement> list = elems;
// IList<IWebElement> list = driver.FindElements(By.PartialLinkText(text));
  • element.Text是您想要的字符串类型,无需调用ToString()
lists.First().Text.ToString();
// lists.First().Text;
  • 如果没有框架,你就不需要这个
driver.SwitchTo().DefaultContent();
  • (来自您之前的文章)IWebElement的列表永远不会等于一个字符串,并且结果不可能是一个元素。如果你不知道自己想要什么类型的var,请避免使用,因为它可能会给你带来完全不同的东西
IList<IWebElement> list = elems;
var elem= list.Equals(text);
  • (来自您之前的帖子)element.ToString()element.Text不同
string targetele = elem.ToString(); // you want elem.Text;