如何单击链接并在新选项卡SeleniumWebDriverC#中打开它



我很难弄清楚如何使用selenium Webdriver在新选项卡中打开链接。我在循环中得到了过时的异常,因为在第一次迭代后页面不正确。因此,我的想法是打开一个新选项卡中的链接,在该选项卡上执行我想做的所有操作,然后切换回旧选项卡以继续循环,但我不太确定如何打开这些选项卡并管理它们。

string year = this.yearTextBox2.Text;
string semester = this.semesterTextBox2.Text;
int numCourses = (int)this.numEnrollments.Value;
int count = 0;
string URL = GetURL(year, semester, "index");
_driver.Navigate().GoToUrl(URL);
//var result = _driver.FindElement(By.XPath("//*[@id="uu-skip-target"]/div[2]/div"));
var results = _driver.FindElements(By.CssSelector(".btn.btn-light.btn-block"));
// Loop through each department
foreach (var r in results)
{
// Make sure not to include the letter link
// Click on this department and get the list of all courses
r.Click();
var result2 = _driver.FindElement(By.Id("class-details"));
var results2 = result2.FindElements(By.XPath("./*[@class="class-info card mt-3"]"));
var courseCount = 0;
// Loop through each course in the department
foreach (var r2 in results2)
{
// Stop the process once reached the amount of courses needed to be scraped
if (count >= numCourses)
break;
Course c = new Course();
c.year = year;
c.semester = semester;
var header = r2.FindElement(By.TagName("h3"));
if (header != null)
{
// Gets the course (CS 2420)
string courseNum = header.Text.Split('-')[0].Trim().ToUpper();
string[] depAndNum = courseNum.Split(' ');
// Separate department and number
c.department = depAndNum[0];
c.number = depAndNum[1];
// Get the course title
string text = header.Text.Split('-')[1].Trim();
c.title = text.Substring(4);
// Check if the course is a lecuture/seminar, if not then continue.
var list = result2.FindElement(By.CssSelector(".row.breadcrumb-list.list-unstyled"));
if (CourseIsLecture(list.FindElements(By.TagName("li"))))
{
c.count = courseCount;
GetCourseInformation(r2, c);
}
else
{
courseCount++;
continue;
}
}
// Increment the course count on this department page
courseCount++;
// Increment total course count
count++;
}
}

您可以在按住控制键的同时执行单击,以强制打开新选项卡中的链接。您可以使用API操作。

Actions action = new Actions(webDriver);
action.KeyDown(Keys.LeftControl).Click(r).KeyUp(Keys.LeftControl).Build().Perform();

然而,我相信,当您回到选项卡0并继续在结果集合上循环时,您可能仍然会得到一个过时的引用异常。如果碰巧是这种情况,您可以首先检索计数,并将foreach循环转换为while/for循环,每次在while/ffor循环内查找结果集合,然后使用results[i]进一步处理该元素。另一种选择是将循环封装在重试块中,例如在引用过时的情况下再次使用Polly框架和查找结果集合,然后重试整个过程。

相关内容

  • 没有找到相关文章

最新更新