Selenium data creation process

dont repeat
The provided code for automating browser interactions using Selenium in C# appears well-structured, but there are a few points and suggestions to address the error and improve the overall reliability of the script:
-
Ensure ChromeDriver Path and Chrome Installation:
Make sure that ChromeDriver is in the system's PATH, or provide an explicit path to ChromeDriver. Also, ensure that Chrome is installed in the expected location. -
Configure ChromeDriver Options:
Use additional ChromeOptions to avoid potential issues with sandboxing and memory usage. -
Use WebDriverWait for Synchronization:
ReplaceThread.SleepwithWebDriverWaitto make the script more reliable and responsive. -
Handle Exceptions Gracefully:
Enhance exception handling to catch specific exceptions and provide more detailed error messages.
Here’s the revised code with these improvements:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading;
namespace SeleniumCourseLoader
{
class Program
{
static void Main(string[] args)
{
Logger.InitLogFile();
Logger.Log("Program started!");
.AddJsonFile("F:\\source\\SeleniumThinkific\\SeleniumThinkific\\appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
string email = configuration["Login:Email"];
string password = configuration["Login:Password"];
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
Logger.Log("Email or password are not set in the configuration file.");
return;
}
ChromeOptions options = new ChromeOptions();
options.AddArgument(@"user-data-dir=C:\Users\Pexabo\AppData\Local\Google\Chrome\User Data"); // Replace with your Chrome user data path
options.AddArgument(@"profile-directory=Profile 15"); // Replace with your profile directory
options.AddArgument("--no-sandbox");
options.AddArgument("--disable-dev-shm-usage");
options.AddArgument("--disable-gpu");
driver.Manage().Window.Size = new System.Drawing.Size(1273, 672);
try
{
Logger.Log("Navigating to login page...");
driver.Navigate().GoToUrl("https://courses.devops.engineering/users/sign_in");
PerformLogin(driver, email, password);
ProcessCourses(driver);
}
catch (Exception ex)
{
Logger.Log($"Test failed: {ex.Message}");
}
finally
{
driver.Quit();
}
Logger.Log("Program ended!");
}
static void PerformLogin(IWebDriver driver, string email, string password)
{
try
{
Logger.Log("Performing login...");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("user[email]"))).SendKeys(email);
driver.FindElement(By.Id("user[password]")).SendKeys(password);
driver.FindElement(By.CssSelector(".button-primary")).Click();
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("user[email]"))).SendKeys(email);
driver.FindElement(By.Id("user[password]")).SendKeys(password);
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(".button-primary"))).Click();
Logger.Log("Login performed successfully.");
}
catch (Exception ex)
{
Logger.Log($"Login failed: {ex.Message}");
}
}
static bool CheckSectionExists(IWebDriver driver, string sectionTitle)
{
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
foreach (var section in sections)
{
if (section.Text.Contains(sectionTitle, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while checking for the section: {ex.Message}");
return false;
}
}
static void ProcessCourses(IWebDriver driver)
{
Logger.Log("Processing courses...");
foreach (var course in courses)
{
Logger.Log($"Processing course: {course.MainUrl}");
driver.Navigate().GoToUrl(course.MainUrl);
Thread.Sleep(5000);
foreach (var section in course.Sections)
{
if (!CheckSectionExists(driver, section.Name))
{
AddChapter(driver, section);
foreach (var video in section.Videos)
{
AddVideo(driver, course.MainUrl, section, video);
}
}
}
}
Logger.Log("Courses processed successfully.");
}
static void AddChapter(IWebDriver driver, Section section)
{
Logger.Log($"Adding chapter: {section.Name}");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button[data-qa='add-chapter__btn']"))).Click();
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//input[@data-qa='chapter-name__input']"))).SendKeys(section.Name);
IWebElement sectionInputField = driver.FindElement(By.XPath("//input[@data-qa='chapter-name__input']"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].value='';", sectionInputField);
sectionInputField.Clear();
sectionInputField.SendKeys(section.Name);
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button[data-qa='actions-bar__save-button']"))).Click();
Thread.Sleep(5000);
string url = driver.Url;
string[] parts = url.Split('/');
string chapterId = parts[parts.Length - 2]; // Second last part is the chapter ID
Logger.Log($"Chapter ID: {chapterId}"); // Output the chapter ID
Thread.Sleep(5000);
section.ChapterId = chapterId; // Store the chapter ID for later use
}
static void AddVideo(IWebDriver driver, string mainUrl, Section section, Video video)
{
Logger.Log($"Adding video: {video.Name} to section: {section.Name}");
driver.Navigate().GoToUrl(mainUrl + "/chapters/" + section.ChapterId + "/contents/new_video_lesson");
Thread.Sleep(7000);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("label[for='lesson-draft-status']"))).Click();
wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("input[data-qa='lesson-form__name']"))).SendKeys(video.Name);
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//button[@data-qa='actions-bar__save-button']"))).Click();
Thread.Sleep(5000);
try
{
IWebElement toastMessage = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div[class^='Toast_toast__message_']")));
toastMessage.Click();
Thread.Sleep(1000);
}
catch (Exception ex)
{
Logger.Log($"Error handling toast message: {ex.Message}");
}
}
}
public static class Logger
{
private static string logFilePath = "logfile.txt";
public static void InitLogFile()
{
if (File.Exists(logFilePath))
{
File.Delete(logFilePath);
}
using (StreamWriter sw = File.CreateText(logFilePath))
{
sw.WriteLine($"Log file created on {DateTime.Now}");
}
}
public static void Log(string message)
{
string logMessage = $"{DateTime.Now}: {message}";
Console.WriteLine(logMessage);
using (StreamWriter sw = File.AppendText(logFilePath))
{
sw.WriteLine(logMessage);
}
}
}
}
Key Changes:
-
Improved Synchronization:
-
Replaced
Thread.SleepwithWebDriverWaitto handle dynamic loading elements more effectively. -
Error Handling:
-
Enhanced error handling with detailed log messages.
-
ChromeDriver Configuration:
-
Added more ChromeOptions for improved stability.
By implementing
these changes, the script should be more robust and less prone to timing issues and errors related to ChromeDriver.

Imported from rifaterdemsahin.com · 2024