Để dùng được Selenium FirefoxDriver trên .Net cần các thư viện trong NugePackage:
- Selenium.Support
- Selenium.WebDriver
Lưu ý. Không add thừa thư viện nếu không muốn dính lỗi cả năm tìm không ra cách sửa.
Chạy Webbrowser cơ bản (khuyến khích sài cái này để rõ ràng)
IWebBrowser driver = new FirefoxDriver();
driver.Url = "https://www.howkteam.com/" ;
driver.Navigate();
hoặc
IWebBrowser driver = new FirefoxDriver();
driver.Navigate().GoToUrl("https://www.howkteam.com/" );
Lấy source page hiện tại
Lấy địa chỉ URL hiện tại
Chuyển tới trang trước đó:
Chuyển tới trang sau đó:
driver.Navigate().Forwad()
F5(Refresh) lại trang:
driver.Navigate().Refresh()
Handle arlet:
IAlert a = driver.SwitchTo().Alert();
a.Accept();
a.Dismiss();
Chuyển đổi giữa các cửa sổ hoặc tab:
ReadOnlyCollection<string > windowHandles = driver.WindowHandles;
string firstTab = windowHandles.First();
string lastTab = windowHandles.Last();
driver.SwitchTo().Window(lastTab);
Maximize window:
this .driver.Manage().Window.Maximize();
Add cookies:
Cookie cookie = new OpenQA.Selenium.Cookie("key" , "value" );
this .driver.Manage().Cookies.AddCookie(cookie);
Get all cookies:
var cookies = this .driver.Manage().Cookies.AllCookies;
Delete cookie:
this .driver.Manage().Cookies.DeleteCookieNamed("CookieName" );
Delete all cookies:
this .driver.Manage().Cookies.DeleteAllCookies();
Chụp màn hình:
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"pathToImage" , ImageFormat.Png);
@pathToImage là đường dẫn tới file hình sẽ lưu.
Đợi đến khi website load xong hết các đoạn 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 đổi giữa các frames:
this .driver.SwitchTo().Frame(1 );
this .driver.SwitchTo().Frame("frameName" );
IWebElement element = this .driver.FindElement(By.Id("id" ));
this .driver.SwitchTo().Frame(element);
Chuyển tới document mặc định:
this .driver.SwitchTo().DefaultContent();
Các locator mặc định(Lấy đối tượng):
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']" ));
Để lấy XPath thì dùng Chrome chọn Kiểm tra phần tử → Nhấp phải vào source của phần tử chọn Coppy → Coppy XPath
Để lấy Css Selector thì dùng Firefox làm tương tự Chrome nhưng chọn Coppy Css Selector
Lấy all element theo điều kiện nào đó:
IReadOnlyCollection<IWebElement> anchors = this .driver.FindElements(By.TagName("a" ));
Tìm 1 element trong 1 element khác:
var div = this .driver.FindElement(By.TagName("div" )).FindElement(By.TagName("a" ));
bản chất 1 element có hàm FindElement nên cứ dùng thêm locator là xong
Một số hàm tham khảo cơ bản:
IWebElement element = driver.FindElement(By.Id("id" ));
element.Click();
element.SendKeys("someText" );
element.Clear();
element.Submit();
string innerText = element.Text;
bool isEnabled = element.Enabled;
bool isDisplayed = element.Displayed;
bool isSelected = element.Selected;
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;
Một số hàm tham khảo nâng cao:
IWebElement element =
driver.FindElement(By.XPath("//*[@id='project']/p[1]/div/div[2]" ));
Actions move = new Actions(driver);
move.DragAndDropToOffset(element, 30 , 0 ).Perform();
Assert.IsTrue(driver.FindElement(By.XPath("//*[@id='tve_editor']/div" )).Displayed);
IWebElement element = driver.FindElement(By.Id("RadUpload1file0" ));
String filePath = @"D:WebDriver.Series.TestsWebDriver.xml" ;
element.SendKeys(filePath);
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();
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);
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post" ));
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30 ));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div" )));
Chụp hình một element
public static Bitmap GetElementScreenShort (IWebDriver driver, IWebElement element)
{
string js = string .Format("window.scroll(0, {0});" , element.Location.Y);
((IJavaScriptExecutor)driver).ExecuteScript(js);
element.Click();
Thread.Sleep(TimeSpan.FromSeconds(2 ));
Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
var img = Image.FromStream(new MemoryStream(sc.AsByteArray)) as Bitmap;
return img.Clone(new Rectangle(new Point(element.Location.X, element.Location.Y -50 ), element.Size), img.PixelFormat);
}
Thực hiện JavaScript với FireFox:
((IJavaScriptExecutor)driver).ExecuteScript("chuỗi code js" );
Thực hiện JavaScript với Chrome:
driver.ExecuteScript("Chuỗi code js" );
Code Configuration tham khảo:
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER" );
IWebDriver driver = new FirefoxDriver(profile);
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);
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);
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.AcceptUntrustedCertificates = true ;
firefoxProfile.AssumeUntrustedCertificateIssuer = false ;
IWebDriver driver = new FirefoxDriver(firefoxProfile);
DesiredCapabilities capability = DesiredCapabilities.Chrome();
Environment.SetEnvironmentVariable("webdriver.chrome.driver" , "C:PathToChromeDriver.exe" );
capability.SetCapability(CapabilityType.AcceptSslCertificates, true );
IWebDriver driver = new RemoteWebDriver(capability);
ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER" );
profile.SetPreference("javascript.enabled" , false );
IWebDriver driver = new FirefoxDriver(profile);
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10 ));
FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"C:extensionsLocationextension.xpi" );
IWebDriver driver = new FirefoxDriver(profile);
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);
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);
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 );
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);
Cài đặt profile cho firefox:
private IWebDriver driver;
string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%APPDATA%" ) + @"\Mozilla\Firefox\Profiles\" ;
string [] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default" , SearchOption.TopDirectoryOnly);
if (pathsToProfiles.Length != 0 )
{
FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0 ]);
profile.SetPreference("browser.tabs.loadInBackground" , false );
driver = new FirefoxDriver(profile);
}
else
{
driver = new FirefoxDriver();
}
Upload file:(Kết hợp auto IT)
AutoItX3 autoIT = new AutoItX3();
autoIT.WinActivate("File Upload" );
autoIT.Send("Đường dẫn đến file cần đưa lên" );
Thread.Sleep(TimeSpan.FromSeconds(1 ));
autoIT.Send("{ENTER}" );
Add references là file AutoITX3 hoặc X3_64 vào. thường là X3 thôi
Đường dẫn tải library
Nếu có lỗi thì thử:
Unlock file AutoITX3(nhấp phải chọn Properties → Unlock → ok)
Theo các step này (k dc thì từ giã)
2. After download completes, Copy & paste it in c:\autoit\PASTE HERE (c:\autoit\AutoItX3.dll)
3. Open Command Prompt as an ‘Adminstrator’
4. In Command Prompt>cd c:\windows\systems32 [Press Enter]
5. c:\windows\systems32>regsvr32 c:\autoit\AutoItX3.dll [Press Enter]
6. Prompt will appear with message “registration Succeeded”
Tải xuống
Tài liệu
Nhằm phục vụ mục đích học tập Offline của cộng đồng, Kteam hỗ trợ tính năng lưu trữ nội dung bài học Selenium FirefoxDriver ChromeDriver .Net | Notes dưới dạng file PDF trong link bên dưới.
Ngoài ra, bạn cũng có thể tìm thấy các tài liệu được đóng góp từ cộng đồng ở mục TÀI LIỆU trên thư viện Howkteam.com
Đừng quên like và share để ủng hộ Kteam và tác giả nhé!
Thảo luận
Nếu bạn có bất kỳ khó khăn hay thắc mắc gì về khóa học, đừng ngần ngại đặt câu hỏi trong phần BÌNH LUẬN bên dưới hoặc trong mục HỎI & ĐÁP trên thư viện Howkteam.com để nhận được sự hỗ trợ từ cộng đồng.
Để dùng được Selenium FirefoxDriver trên .Net cần các thư viện trong NugePackage:
- Selenium.Support
- Selenium.WebDriver
hay