❅
❅
❆
❅
❆
❅
❆
❅
❆
❆

  • 0939206009
  • thaian.it15@gmail.com
  • Facebook
  • Youtube
  • Zalo
Anh Tester Logo
  • Khoá học
    • All Courses
    • Website Testing
    • API Testing
    • Desktop Testing
    • Mobile Testing
    • Programming Language
    • CI/CD for Tester
    • Performance Testing
  • 💥Khai giảng
  • tools
    • TestGenAI - AI Test Cases Generator
    • Mobile Apps Demo
    • Automation Framework Selenium TestNG
    • Automation Framework Cucumber TestNG
    • Gherkin Convert Functions in Katalon
    • Convert object from Selenium Java to Playwright Python
    • Website Demo CRM
    • Website Demo HRM
    • Website Demo HRM GO
    • Website Demo POS
    • Website Demo eCommerce CMS
  • blog
    • Selenium C#
    • Selenium Java
    • Katalon Tools
    • Jenkins CI/CD
    • SQL cho Tester
    • Manual Testing
    • Tài liệu cho Tester
    • Automation Testing
    • akaAT Tools
    • Cucumber TestNG
    • API Testing with Postman
    • Apache Maven
    • AI in Software Testing
    • Lịch khai giảng
  • Liên hệ
  • Log in
    Sign up

Các lệnh truy vấn trong Selenium WebDriver C#

  • Blog
  • Automation Testing
Các lệnh truy vấn trong Selenium WebDriver C#

Các lệnh truy vấn trong Selenium WebDriver C#

  • Anh Tester
  • Automation Testing
  • 16964
Anh Tester đã chia sẻ cho các bạn Cheat sheet về Selenium Java rồi thì hôm nay An tiếp tục gom các câu lệnh trong Selenium C# lại để các bạn dễ theo dõi học tập làm việc về nó hơn.

Initialize

Các cách khởi tạo Driver với các loại trình duyệt khác nhau và Import thư viện (using) tương ứng

// Chrome Driver
using OpenQA.Selenium.Chrome;
IWebDriver driver = new ChromeDriver();
// Firefox Webdriver
using OpenQA.Selenium.Firefox;
IWebDriver driver = new FirefoxDriver();
// PhantomJS
using OpenQA.Selenium.PhantomJS;
IWebDriver driver = new PhantomJSDriver();
// IE Driver
using OpenQA.Selenium.IE;
IWebDriver driver = new InternetExplorerDriver();
// Edge Driver
using OpenQA.Selenium.Edge;
IWebDriver driver = new EdgeDriver();

Locators

Bộ định vị, tìm Element theo các kiểu khác nhau

this.driver.FindElement(By.ClassName("className"));
this.driver.FindElement(By.CssSelector("css"));
this.driver.FindElement(By.Id("id"));
this.driver.FindElement(By.LinkText("text"));
this.driver.FindElement(By.Name("name"));
this.driver.FindElement(By.PartialLinkText("pText"));
this.driver.FindElement(By.TagName("input"));
this.driver.FindElement(By.XPath("//*[@id='editor']"));
// Tìm nhiều Element chung kiểu
IReadOnlyCollection<IWebElement> anchors = this.driver.FindElements(By.TagName("a"));
// Tìm kiếm một phần tử bên trong một phần tử khác
var div = this.driver.FindElement(By.TagName("div")).FindElement(By.TagName("a"));

Basic Elements Operations

Các kiểu hành động của Element

IWebElement element = driver.FindElement(By.Id("id"));
element.Click(); //Sẽ nhấp chuột vào bất kỳ phần tử nào. Không chấp nhận tham số và không trả về gì cả (chỉ là hành động click).
element.SendKeys("someText"); //Nhập giá trị
element.Clear(); //Xóa giá trị dạng chuỗi (trong input/textarea)
element.Submit(); //Phương thức này cũng gần giống như Click() nhưng nó sẽ chuẩn xác hơn nếu phần tử hiện tại là một biểu mẫu hoặc một phần tử trong một biểu mẫu.
string innerText = element.Text; //Phương thức này sẽ tìm nạp tệp innerText hiển thị (tức là không bị ẩn bởi CSS) của phần tử. Nó không chấp nhận tham số và trả về một giá trị Chuỗi.
bool isEnabled = element.Enabled; //Phương pháp này xác định xem một phần tử hiện đang được Bật hay không. (Dành cho validate button Hiện/Ẩn)
bool isDisplayed = element.Displayed; //Phương pháp này xác định xem một phần tử hiện đang được hiển thị hay không. Điều này không chấp nhận tham số nhưng trả về giá trị boolean (true/false).
bool isSelected = element.Selected; //Xác định xem phần tử này có được chọn hay không. Không chấp nhận tham số nhưng trả về giá trị boolean (true / false).
IWebElement element = driver.FindElement(By.Id("id"));
SelectElement select = new SelectElement(element);
select.SelectByIndex(1);
select.SelectByText("Ford");
select.SelectByValue("ford");           
select.DeselectAll();
select.DeselectByIndex(1);
select.DeselectByText("Ford");
select.DeselectByValue("ford");
IWebElement selectedOption = select.SelectedOption;
IList<IWebElement> allSelected = select.AllSelectedOptions;
bool isMultipleSelect = select.IsMultiple;​

Advanced Elements Operations

Các loại hành động nâng cao hơn
// Kéo và Thả
IWebElement element = 
driver.FindElement(By.XPath("//*[@id='project']/p[1]/div/div[2]"));
Actions move = new Actions(driver);
move.DragAndDropToOffset(element, 30, 0).Perform();
// Cách kiểm tra xem một phần tử có hiển thị không
Assert.IsTrue(driver.FindElement(By.XPath("//*[@id='tve_editor']/div")).Displayed);
// Upload một File
IWebElement element = driver.FindElement(By.Id("RadUpload1file0"));
String filePath = @"D:WebDriver.Series.TestsWebDriver.xml";
element.SendKeys(filePath);
// Cuộn thanh chuột để điều khiển đến vị trí Element
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));
string js = string.Format("window.scroll(0, {0});", link.Location.Y);
((IJavaScriptExecutor)driver).ExecuteScript(js);
link.Click();
// Chụp ảnh màn hình phần tử
IWebElement element = driver.FindElement(By.XPath("//*[@id='tve_editor']/div"));
var cropArea = new Rectangle(element.Location, element.Size);
var bitmap = bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
bitmap.Save(fileName);
// Truy cập đến liên kết của phần tử chứa link có tên như bên dưới
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));
// Chờ một phần tử hiển thị
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div")));​

Basic Browser Operations

Các thao tác trình duyệt cơ bản
// Chuyển hướng đến 1 trang chỉ định    
this.driver.Navigate().GoToUrl(@"http://google.com");
// Lấy tiêu đề của trang
string title = this.driver.Title;
// Lấy đường dẫn url hiện tại
string url = this.driver.Url;
// Lấy cái source html của trang hiện tại (dạng chuỗi)
string html = this.driver.PageSource;​

Advanced Browser Operations

Các thao tác trình duyệt nâng cao
// Đi đến 1 alert và thao tác
IAlert a = driver.SwitchTo().Alert();
a.Accept();
a.Dismiss();
// Chuyển đổi các Tab của trình duyệt hiện tại
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
string firstTab = windowHandles.First();
string lastTab = windowHandles.Last();
driver.SwitchTo().Window(lastTab);
// Điều hướng về lịch sử trang trước đó
this.driver.Navigate().Back();
// Làm mới trang hiện tại
this.driver.Navigate().Refresh();
// Điều hướng đến trang tiếp sau
this.driver.Navigate().Forward();
// Điền chuỗi
link.SendKeys(string.Empty);
// Đi đến link và chọn link
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].focus();", link);
// Phóng hết cỡ trình duyệt theo full màn hình máy tính
this.driver.Manage().Window.Maximize();
// Thêm cookie mới với Key và Value chỉ định
Cookie cookie = new OpenQA.Selenium.Cookie("key", "value");
this.driver.Manage().Cookies.AddCookie(cookie);
// Lấy tất cả cookies của driver hiện tại
var cookies = this.driver.Manage().Cookies.AllCookies;
// Xóa một cookie theo tên
this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");
// Xóa tất cả các cookies
this.driver.Manage().Cookies.DeleteAllCookies();
//Chụp ảnh màn hình toàn màn hình
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"pathToImage", ImageFormat.Png);
// Chờ cho đến khi một trang được tải đầy đủ qua JavaScript
WebDriverWait wait = new WebDriverWait(this.driver, TimeSpan.FromSeconds(30));
wait.Until((x) =>
{
    return ((IJavaScriptExecutor)this.driver).ExecuteScript("return document.readyState").Equals("complete");
});
// Chuyển sang khung hiển thị trên trình duyệt được chỉ định các kiểu sau:
this.driver.SwitchTo().Frame(1); //khung hiển thị đầu
this.driver.SwitchTo().Frame("frameName"); //khung hiển thị theo tên
IWebElement element = this.driver.FindElement(By.Id("id"));
this.driver.SwitchTo().Frame(element); //khung hiển thị chứa element có ID chỉ định
// Chuyển sang khung hiển thị trên trình duyệt hiện tại
this.driver.SwitchTo().DefaultContent();​

// Chuyển tới lớp hiển thị sau cùng (cửa sổ hiện tại)
driver.SwitchTo().Window(driver.WindowHandles.Last());

Advanced Browser Configurations

Cấu hình trình duyệt nâng cao

// Sử dụng một cấu hình Firefox cụ thể
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
IWebDriver driver = new FirefoxDriver(profile);
// Đặt một proxy HTTP cho Firefox
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("network.proxy.type", 1);
firefoxProfile.SetPreference("network.proxy.http", "myproxy.com");
firefoxProfile.SetPreference("network.proxy.http_port", 3239);
IWebDriver driver = new FirefoxDriver(firefoxProfile);
// Đặt proxy HTTP cho Chrome
ChromeOptions options = new ChromeOptions();
var proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3239";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
// Chấp nhận tất cả các chứng chỉ Firefox
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.AcceptUntrustedCertificates = true;
firefoxProfile.AssumeUntrustedCertificateIssuer = false;
IWebDriver driver = new FirefoxDriver(firefoxProfile);
// Chấp nhận tất cả các chứng chỉ Chrome
DesiredCapabilities capability = DesiredCapabilities.Chrome();
Environment.SetEnvironmentVariable("webdriver.chrome.driver", "C:PathToChromeDriver.exe");
capability.SetCapability(CapabilityType.AcceptSslCertificates, true);
IWebDriver driver = new RemoteWebDriver(capability);
// Đặt tùy chọn cho Chrome.
ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Tắt JavaScript trên Firefox
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
profile.SetPreference("javascript.enabled", false);
IWebDriver driver = new FirefoxDriver(profile);
// Đặt thời gian chờ tải trang mặc định (đơn vị giây)
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10));
// Khởi động Firefox bằng các plugin (thêm vào từ local của máy tính mình)
FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"C:extensionsLocationextension.xpi");
IWebDriver driver = new FirefoxDriver(profile);
// Khởi động Chrome bằng tiện ích mở rộng được giải nén
ChromeOptions options = new ChromeOptions();
options.AddArguments("load-extension=/pathTo/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Khởi động Chrome bằng một tiện ích mở rộng được đóng gói
ChromeOptions options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("localpathto/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Thay đổi vị trí lưu của tệp mặc định
String downloadFolderPath = @"c:temp";
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", downloadFolderPath);
profile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
//Các loại tệp sau thì lưu không cần hỏi (neverAsk)
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", 
"application/msword, application/binary, application/ris, text/csv, image/png, application/pdf,
text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, 
application/octet-stream");
this.driver = new FirefoxDriver(profile);​
  • Tags:
  • Selenium C#
  • Cheat sheet
  • Selenium
  • Automation Test

Chia sẻ bài viết

Facebook Linkedin Telegram Pinterest Share with Zalo Zalo

Cộng đồng Automation Testing Việt Nam

🌱 Facebook Fanpage: Anh Tester
🌱 Telegram
Automation Testing:   Cộng đồng Automation Testing
🌱 
Facebook Group Automation: Cộng đồng Automation Testing Việt Nam
🌱 Telegram
Manual Testing:   Cộng đồng Manual Testing
🌱 
Facebook Group Manual: Cộng đồng Manual Testing Việt Nam

  • Anh Tester

    Anh Tester

    Đường dẫu khó chân vẫn cần bước đi
    Đời dẫu khổ tâm vẫn cần nghĩ thấu

    • Facebook
    • Youtube
    • Zalo

Search Blogs

Related Blogs

🤖 So sánh Playwright JS/TS và Playwright Python

🤖 So sánh Playwright JS/TS và Playwright Python

Aug-29-2025 by Anh Tester
So sánh Playwright và Selenium trong Test Automation

So sánh Playwright và Selenium trong Test Automation

Aug-23-2025 by Anh Tester
🚀 Lộ trình học Automation Tester tại Anh Tester

🚀 Lộ trình học Automation Tester tại Anh Tester

Aug-23-2025 by Anh Tester
Những kỹ năng cần có cho level Senior Automation Tester

Những kỹ năng cần có cho level Senior Automation Tester

Dec-17-2024 by Anh Tester
Những kỹ năng cần có cho level Middle Automation Tester

Những kỹ năng cần có cho level Middle Automation Tester

Dec-17-2024 by Anh Tester
Những kỹ năng cần có cho level Junior Automation Tester

Những kỹ năng cần có cho level Junior Automation Tester

Dec-17-2024 by Anh Tester
Những kỹ năng cần có cho level Fresher Automation Tester

Những kỹ năng cần có cho level Fresher Automation Tester

Dec-17-2024 by Anh Tester
Cách xử lý các Exceptions trong Selenium WebDriver

Cách xử lý các Exceptions trong Selenium WebDriver

May-31-2024 by Anh Tester
Tại sao chúng ta cần Kiểm thử Tự động

Tại sao chúng ta cần Kiểm thử Tự động

May-30-2024 by Anh Tester
How to get HTML5 validation message with Selenium

How to get HTML5 validation message with Selenium

Mar-22-2024 by Anh Tester
view all

Blog Tags

  • Selenium
  • Xpath
  • Locator
  • Jenkins
  • Testing
  • Tester
  • Thuật ngữ
  • Lộ trình
  • Khóa học
  • Mindset
  • QA
  • QC
  • Checklist
  • Website
  • Mobile
  • Question
  • Answer
  • Phỏng vấn
  • Extension
  • Cucumber
  • Gherkin
  • Agile
  • Scrum
  • Document
  • Testing Level
  • Automation Test
  • Test Cases
  • Trường hợp
  • Katalon
  • JMeter
  • Postman
  • API
  • Manual Test
  • Developer

Anh Tester

Anh Tester profile
Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu

Connect me on

  • Facebook
  • Youtube
  • Zalo


Liên hệ

  • 0939206009
  • thaian.it15@gmail.com
  • Anh Tester
  • Donate for Anh Tester
QR Facebook Group
QR Discord Group

Copyright © 2021-2025 Anh Tester Automation Testing