【发布时间】:2021-12-21 12:48:12
【问题描述】:
我无法弄清楚如何使用 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++;
}
}
【问题讨论】:
标签: c# selenium selenium-webdriver selenium-chromedriver