IE attachment using selenium - c#

Is it possible to attach in an open internet explorer using selenium?
I've already read lots of forums about this, and they always said that it is possible for IE and not on other browsers. But the problem is, there is no available example or instruction on how to implement it.

I dont know about Internet Explorer, but you can connect to an opened firefox browser if this browser instance is previously opened by WebDriver.
IWebDriver WebDriver = null;
try
{
System.Uri uri = new System.Uri("http://localhost:7055/hub");
WebDriver = new RemoteWebDriver(uri, DesiredCapabilities.Firefox());
Console.WriteLine("Executed on remote driver");
}
catch (Exception)
{
WebDriver = new FirefoxDriver(firefoxProfile);
Console.WriteLine("Executed on New FireFox driver");
}
see this blog post for more details
http://binaryclips.com/2014/09/16/selenium-web-driver-in-c-how-to-continue-script-on-the-already-opened-browser-instance/

Related

How to send whatsapp messages with selenium in an existing WhatsappWeb connection

I tried to send messages to whatsapp with Selenium and C#.
The problem is that, if as an example I am connected to Whatsapp in the current Chrome profile, when the WebDriver is initialized it open a new chrome, without profile and with whatsapp scan QR code.
I want to send messages using the existing browser connection.
I have tried:
var chromeOptions = new ChromeOptions();
chromeOptions.AddExcludedArgument("enable-automation");
chromeOptions.AddAdditionalChromeOption("useAutomationExtension", false);
driver = new ChromeDriver(chromeOptions);
driver.Navigate().GoToUrl("https://web.whatsapp.com/");
And also:
var chromeOptions = new ChromeOptions();
chromeOptions.AddExcludedArgument("enable-automation");
chromeOptions.AddArgument("--user-data-dir=chrome-data");
chromeOptions.AddAdditionalChromeOption("useAutomationExtension", false);
driver = new ChromeDriver(chromeOptions);
driver.Navigate().GoToUrl("https://web.whatsapp.com/");
What I want: to open a new chrome instance, with the existing whatsapp connection,
You need to load the correct profile.
This is the answer provided from uzumaki on how to achieve that:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_argument(r"--user-data-dir=C:\path\to\chrome\user\data") #e.g. C:\Users\You\AppData\Local\Google\Chrome\User Data
options.add_argument(r'--profile-directory=YourProfileDir') #e.g. Profile 3
driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe', chrome_options=options)
driver.get("https://www.google.co.in")

Click on HTML elements with Scrapy (WebScraping)

I'm doing a program in c # using scrapySharp or HtmlAgilityPack. But I have the disadvantage of that part of the information that I need, to appear when I click on an HTML element (Button, link ).
In some forums it was commented that when using Selenium you could manipulate the html elements, so I tried the following
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
// Defines the interface with the Chrome browser
IWebDriver driver = new ChromeDriver ();
// Auxiliary to store the label element in href
Element IWebElement;
// Go to the website
driver.Url = url;
// Click on the download button
driver.FindElement (By.Id ("Download button")). Click ();
but being a web automation test, it opens a browser and the website to perform the selection process (clicks), so it is not of my use, since I have to perform the inspection on several websites internally.
Although I can continue using Selenium, I am looking for ways to avoid using the browser and instead click without it.
Does anyone know how to achieve the click of the link or button, without the need to open a browser for web scraping?
Hope this would be helpful to anyone who has the same requirements.
If you want to avoid opening the browser, you could use below settings in the ChromeDriver.
// settings for avoid opening browser
var options = new ChromeOptions();
options.AddArgument("headless");
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
// url to access and scrape
var url = "https://example.com";
using (var driver = new ChromeDriver(service, options))
{
// access the url
driver.Navigate().GoToUrl(url);
// Click on the download button - copied from your code above
driver.FindElement (By.Id ("Download button")). Click ();
}
In addition to above below links also, you may find useful,
can-selenium-webdriver-open-browser-windows-silently-in-background
running-webdriver-without-opening-actual-browser-window

Can title of browser be changed in selenium c#?

In Selenium using Webdriver and C# how we can change the browser title?
Using javascript and jQuery as follow:
document.title='XXX'
or
$('title')[0].text='XXX'
Have no effect although we can change the title using Web developers tool console.
Is there any restriction in changing browser title in Selenium?
UPDATE:
Problem roots: Using JavaScriptExecutor that has been initialized with the driver on a window which had been closed.
As said in this answer,
you can run javascript code from selenium.
Your code will be like this:
WebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("document.title = 'hello'");
And it will change browser title.
Edit
Here full working code:
ChromeOptions options = new ChromeOptions();
options.AddArguments("--start-maximized");
var driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("http://www.google.com");
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("document.title = 'hello'");
And here result:

Chromedriver: How to disable PDF plugin

To mimic functionality of how my Firefox profile is set up, I need to ensure that the PDF viewer for Chrome is disabled. after searching across the internet, the closest answer I find is here
https://code.google.com/p/chromium/issues/detail?id=528436
However attempting any of the suggestions on this page have given me no success
Here is a snippet of code I expect to work
Dictionary<String, Object> plugin = new Dictionary<String, Object>();
plugin.Add("enabled", false );
plugin.Add("name", "Chrome PDF Viewer");
var options = new ChromeOptions();
options.AddUserProfilePreference("plugins.plugins_list", plugin);
driver = new ChromeDriver(options);
Can anyone see what exactly I am doing wrong? this is starting to become a really frustrating issue!
For Chrome 57, I had to use this line instead:
options.AddUserProfilePreference("plugins.always_open_pdf_externally", true);
Additionally, if you ever need to set a plugin yourself you can find it like this:
Navigate to chrome://settings/content (Menu > Settings, Show advanced settings..., Content settings...).
Locate the specific preference (checkboxes only).
Right-click and Inspect the checkbox.
The preference name is the entire 'pref' attribute's value.
I found that this works for Selenium.WebDriver 2.53m, ChromeDriver 2.25.426923, and Chrome v55.0.2883.87 m.
var options = new ChromeOptions();
options.AddUserProfilePreference("plugins.plugins_disabled", new []{"Chrome PDF Viewer"});
driver = new ChromeDriver(options);
This work for me (if the first link is Chrome PDF Viewer )
driver.Navigate().GoToUrl("chrome://plugins/");
Thread.Sleep(4000);
driver.FindElement(By.LinkText("Disable")).Click();

Selenium WebDriver and browsers select file dialog

I'm using selenium webdriver, C#.
Is it possible to make work webdriver with Firefox select file dialog?
Or must I use something like AutoIt?
If you are trying to select a file for upload Selenium 2 supports HTML file inputs. For example:
HTML
<input type="file" id="uploadhere" />
Selenium Code
IWebElement element = driver.FindElement(By.Id("uploadhere"));
element.SendKeys("C:\\Some_Folder\\MyFile.txt");
Basically you "type" (with SendKeys) the full file path to the file input element. Selenium handles the file selection dialog for you.
However if you want to manipulate an arbitrary file selection dialog, then like Anders said, you have to go outside of Selenium.
No, WebDriver cannot interact with dialogs - this is because dialogs are the domain of the operating system and not the webpage.
I know people that have had luck with autoit as well as the Automation API provided by .Net.
Another option would be to skip the file dialog entirely and issue a POST or a GET, but this requires more advanced knowledge of the website as well as understanding how construct a POST/GET.
You could try Webinator, it is similar to Selenium in the sense that it is powered by WebDriver. It provides file dialog capabilities and I've had great success with it.
Here is another solution using remotewebdriver, it works like magic and I loved it.
Here is the class I have:
driver.findElementByLinkText("Upload Files").click();
driver.setLogLevel(Level.ALL);
System.out.println(driver.getCurrentUrl());
WebElement element = driver.findElement(By.xpath("//input[#name='file_1']"));
LocalFileDetector detector = new LocalFileDetector();
//Now, give the file path and see the magic :)
String path = "D://test66T.txt";
File f = detector.getLocalFile(path);
((RemoteWebElement)element).setFileDetector(detector);
element.sendKeys(f.getAbsolutePath());
//now click the button to finish
driver.findElementByXPath("//html/body/div[9]/div[1]/a/span").click();
You asked for using AutoIt for the file dialog. This is easy and you can do it with C#.
Install nuget package AutoItX.Net
Use the demo code below
Change the dialog title string as you need
public static void InsertIntoFileDialog(string file, int timeout = 10)
{
int aiDialogHandle = AutoItX.WinWaitActive("Save As", "", timeout); // adjust string as you need
if (aiDialogHandle <= 0)
{
Assert.Fail("Can't find file dialog.");
}
AutoItX.Send(file);
Thread.Sleep(500);
AutoItX.Send("{ENTER}");
Thread.Sleep(500);
}
This helped me after I had trouble with Appium/Selenium related to file dialogs.
According to Nadim Saker
.Net has a library to handle file upload dialog. It has a SendKeys class that has a method SendWait(string keys). It sends the given key on the active application and waits for the message to be processed. It does not return any value.
This can be done as follows, tested and working with Internet Explorer and Chrome driver
var allowsDetection = this.Driver as IAllowsFileDetection;
if (allowsDetection != null)
{
allowsDetection.FileDetector = new LocalFileDetector();
}
Driver.FindElement(By.Id("your-upload-input")).SendKeys(#"C:\PathToYourFile");
Reference https://groups.google.com/forum/#!msg/webdriver/KxmRZ8MkM4M/45CT4ID_WjQJ
If you want to upload a file, and not use the WebDriver, the only solution I've come across is AutoIt. It allows you to write a script and convert it to an executable which you can then call from within your code. I've used it successfully while working with an ActiveX control.
Another approach is to use System.Windows.Forms.SendKeys.SendWait("pathToFile"). I use it with success everywhere where i cant just send keys to element like described by #prestomanifesto.
I used this to solve the problem... try it if all above does not works
Actions action = new Actions(driver);
action.SendKeys(pObjElement, Keys.Space).Build().Perform();
Thread.Sleep(TimeSpan.FromSeconds(2));
var dialogHWnd = FindWindow(null, "Elegir archivos para cargar"); // Here goes the title of the dialog window
var setFocus = SetForegroundWindow(dialogHWnd);
if (setFocus)
{
Thread.Sleep(TimeSpan.FromSeconds(2));
System.Windows.Forms.SendKeys.SendWait(pFile);
System.Windows.Forms.SendKeys.SendWait("{DOWN}");
System.Windows.Forms.SendKeys.SendWait("{TAB}");
System.Windows.Forms.SendKeys.SendWait("{TAB}");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
Thread.Sleep(TimeSpan.FromSeconds(2));
}

Categories

Resources