Can't save the session of Whatsapp web with Selenium c# - c#

I want to save session of whatsapp web so I do not have to scan qr-code every time I open whatsapp web. I use:
options.AddArgument("--user-data-dir=" + FolderPathToStoreSession)
but the qr-code appear again.
Here is the method to open whatsapp web for first time to scan qr code and save it to folder:
public static int OpenNewChrome(
string Website,
int TimeToWaitInMinutes,
string FolderPathToStoreSession)
{
ChromeOptions options = null;
ChromeDriver driver = null;
try
{
//chrome process id
int ProcessId = -1;
//time to wait until open chrome
var TimeToWait = TimeSpan.FromMinutes(TimeToWaitInMinutes);
ChromeDriverService cService = ChromeDriverService.CreateDefaultService();
//hide dos screen
cService.HideCommandPromptWindow = true;
options = new ChromeOptions();
//session file directory
options.AddArgument("--user-data-dir=" + FolderPathToStoreSession);
driver = new ChromeDriver(cService, options, TimeToWait);
//set process id of chrome
ProcessId = cService.ProcessId;
driver.Navigate().GoToUrl(Website);
FRM_MSG f2 = new FRM_MSG();
DialogResult r = f2.ShowDLG(" ",
"Did you successfully finish scan bardcode?",
FRM_MSG.MSGIcon.Question,
FRM_MSG.BTNS.Two,
new string[] { "Yes Finish", "Cannot scan qr-code" });
if (driver != null)
{
driver.Close();
driver.Quit();
driver.Dispose();
}
if (r == DialogResult.Yes)
return ProcessId;
return -1;
}
catch (Exception ex)
{
if (driver != null)
{
driver.Close();
driver.Quit();
driver.Dispose();
}
driver = null;
throw ex;
}
}
and here is method to restore session:
public static int OpenOldChrome(
string Website,
int TimeToWaitInMinutes,
string FolderPathToStoreSession)
{
ChromeOptions options = null;
ChromeDriver driver = null;
try
{
//chrome process id
int ProcessId = -1;
//time to wait until open chrome
var TimeToWait = TimeSpan.FromMinutes(TimeToWaitInMinutes);
ChromeDriverService cService = ChromeDriverService.CreateDefaultService();
//hide dos screen
cService.HideCommandPromptWindow = true;
options = new ChromeOptions();
//session file directory
options.AddArgument("--user-data-dir=" + FolderPathToStoreSession);
driver = new ChromeDriver(cService, options, TimeToWait);
//set process id of chrome
ProcessId = cService.ProcessId;
Thread.Sleep(50000);
FRM_MSG f2 = new FRM_MSG();
DialogResult r = f2.ShowDLG(" ",
"Did you wnat to exit?",
FRM_MSG.MSGIcon.Question,
FRM_MSG.BTNS.Two,
new string[] { "Yes", "No" });
if (driver != null)
{
driver.Close();
driver.Quit();
driver.Dispose();
}
if (r == DialogResult.Yes)
return ProcessId;
return -1;
}
catch (Exception ex)
{
if (driver != null)
{
driver.Close();
driver.Quit();
driver.Dispose();
}
driver = null;
throw ex;
}
}
The problem as I said the qr-code appear again, I want to scan qr-code only once
I use google chrome version 74, web driver v 3.141.0.

Do check if the profile folder is correct . An old thread here mention that you need to add \Default to the profile path.
Have you try adding this to see if this helps
options.addArguments("chrome.switches", "--disable-extensions")

Related

What should I change so that Chrome not opens New Window every time when this code triggers

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Threading;
namespace TallyWhatsappsender
{
public class Class1
{
OpenQA.Selenium.IWebDriver chrome_driver = null;
public String InitProcess(String contact,String file_route,String title,String chrome_binary)
{
try
{
if (!System.IO.File.Exists(file_route))
{
return "Error : Attachment not found!";
}
if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe")))
{
return "Error : Chromedriver.exe executable not found!\n chromedriver.exe file is missing\n update or reinstalling may fix the problem";
}
var chrome_driver_service = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe");
chrome_driver_service.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
if (File.Exists(chrome_binary))
{
chromeOptions.BinaryLocation = chrome_binary;
}
chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions);
IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)chrome_driver;
foreach (string ct in contact.Split(','))
{
if (string.IsNullOrEmpty(ct.Trim()))
{
break;
}
if(ct.Trim().Length != 12)
{
if (!(chrome_driver is null)) chrome_driver.Quit();
return "Error : Invalid contact number-" + ct;
}
chrome_driver.Url = "https://web.whatsapp.com/send?phone=" + ct.Trim();
try
{
chrome_driver.SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException e1)
{
Console.WriteLine(e1.Message);
}
try
{
WebDriverWait wait = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]")));
}
catch (WebDriverTimeoutException)
{
continue;
}
//sending file
IWebElement file_open = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[1]/div[2]/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_open);
chrome_driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file_route);
WebDriverWait wait2 = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(30));
wait2.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span")));
IWebElement file_send = chrome_driver.FindElement(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_send);
Thread.Sleep(1000);
//sending text
IWebElement typebox = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]"));//:chrome_driver.FindElements(By.CssSelector("div[class ='_3u328 copyable-text selectable-text']"))[0];
typebox.SendKeys(title);
IWebElement text_send = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[3]/button/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", text_send);
Thread.Sleep(3000);
}
//chrome_driver.Quit();
return "Process finished";
}
//catch (Exception ex)
//{
// if (!(chrome_driver is null)) chrome_driver.Quit();
// return ex.Message;
//}
}
}
}
I am using the above code for exporting a PDF file from tally and send it through Whatsapp Automatically.
I am facing a problem :
Every time I use this option a new tab of chrome opens and closes after sending file, because of new window it asks me to login to whatsapp every time , I think it will sort out if it do not close after sending file or when I activate it , it goes automatically to the previously opened Web.Whatsapp.com so that I will not need authentication each time.
please help me out into this .
Thanks in advance
Every time you call chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions); a new tab opens.
Try separating the initiating process and the sending process.
For example, your InitProcess method could look like the following:
public InitProcess(String chrome_binary)
{
try
{
if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe")))
{
return "Error : Chromedriver.exe executable not found!\n chromedriver.exe file is missing\n update or reinstalling may fix the problem";
}
var chrome_driver_service = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe");
chrome_driver_service.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
if (File.Exists(chrome_binary))
{
chromeOptions.BinaryLocation = chrome_binary;
}
chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions);
return "Intiated";
}
}
And then you could add a Send function:
public String Send(String contact, String file_route, String title)
{
try
{
IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)chrome_driver;
foreach (string ct in contact.Split(','))
{
if (string.IsNullOrEmpty(ct.Trim()))
{
break;
}
if(ct.Trim().Length != 12)
{
if (!(chrome_driver is null)) chrome_driver.Quit();
return "Error : Invalid contact number-" + ct;
}
chrome_driver.Url = "https://web.whatsapp.com/send?phone=" + ct.Trim();
try
{
chrome_driver.SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException e1)
{
Console.WriteLine(e1.Message);
}
try
{
WebDriverWait wait = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]")));
}
catch (WebDriverTimeoutException)
{
continue;
}
//sending file
IWebElement file_open = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[1]/div[2]/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_open);
chrome_driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file_route);
WebDriverWait wait2 = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(30));
wait2.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span")));
IWebElement file_send = chrome_driver.FindElement(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_send);
Thread.Sleep(1000);
//sending text
IWebElement typebox = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]"));//:chrome_driver.FindElements(By.CssSelector("div[class ='_3u328 copyable-text selectable-text']"))[0];
typebox.SendKeys(title);
IWebElement text_send = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[3]/button/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", text_send);
Thread.Sleep(3000);
return "Process finished";
}
}
}
Now you call InitProcess only once at the beginning of you program and Send every time you want to send the file.

Selenium, When I use tabs, chrome keep maxmize even if you minimize it

I make a program and it keeps open and close tabs
SO when a new tab opened or closed, chrome show up again even if it minimize
I need to keep it minimized
This is my code:
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
try
{
try
{
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10);
driver.Navigate().GoToUrl(url);
}
catch (Exception r)
{
((IJavaScriptExecutor)driver).ExecuteScript("return window.stop");
}
var streamdiv = obj.FindElement(driver, "content-audio_html5_api", Assistances.FindElementBy.ID, true);
if (streamdiv != null)
{
var streamurl = streamdiv.FindElement(By.XPath(".//source")).GetAttribute("src");
if ((streamurl != "" || streamurl != null) && streamurl != url.Remove(url.IndexOf('s'), 1))
{
row["streamURL"] = streamurl;
}
}
}
catch (Exception er)
{
row["streamURL"] = "";
}
try
{
string logo_url = driver.FindElement(By.XPath("//div[#class='song-image']//a//img")).GetAttribute("src");
row["logo_URL"] = logo_url;
obj.DownloadImage(logo_url);
}
catch (Exception e)
{
}
driver.Close();
driver.SwitchTo().Window(driver.WindowHandles.First());

Timeout in Selenium Chrome driver

I have a code which triggers 5 console apps (same code base different location).
public static void RunLoadGenInstances(int loadGenInstanceCount, string exePath)
{
try
{
for (int i = 1; i < loadGenInstanceCount; i++)
{
Thread.Sleep(1000);
Process.Start(exePath + i + #"\bin\Debug\wm_uk_hr_loadgen.exe");
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
}
}
Each of the exe inilitializes the ChromeDriver.exe from their own executable path and opens up Chrome.
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("download.default_directory", file_path);
options.AddUserProfilePreference("disable-popup-blocking", "true");
options.AddArguments("--disable-extensions");
options.AddArguments("--start-maximized");
ChromeDriverService service = ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
service.SuppressInitialDiagnosticInformation = true;
service.HideCommandPromptWindow = true;
string url = HRSSUrl;
chromeDriver = new ChromeDriver(service, options);
Thread.Sleep(500);
chromeDriver.Navigate().GoToUrl(url);
Console.WriteLine("Enter uid");
IWebElement idWait = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("__control0-user")));
IWebElement id = chromeDriver.FindElement(By.Id("__control0-user"));
id.SendKeys(c4cUserId);
Console.WriteLine("uid entered");
Console.WriteLine("Enter pwd");
IWebElement passWait = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("__control0-pass")));
IWebElement pass = chromeDriver.FindElement(By.Id("__control0-pass"));
pass.SendKeys(c4cPassword);
Console.WriteLine("pwd entered");
Console.WriteLine("click login");
IWebElement loginWait = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("__control0-logonBtn")));
IWebElement login = chromeDriver.FindElement(By.Id("__control0-logonBtn"));
login.Click();
Problem is- Chrome is able to launch and navigate to URL but it is stuck on Sign In page. This happens in 4 console apps except 1, which runs fine. Below is the exception message which I get from the failed apps.
Enter uid
at OpenQA.Selenium.Support.UI.DefaultWait`1.ThrowTimeoutException(String exce
ptionMessage, Exception lastException)
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at wm_uk_hr_loadgen.Program.SelectAuthenticationDropDown() in c:\UK-HR\LoadGe
n-MultiInstance\LoadGen1\Program.cs:line 273
at wm_uk_hr_loadgen.Program.Main(String[] args) in c:\UK-HR\LoadGen-MultiInst
ance\LoadGen1\Program.cs:line 105
Any help? Please let me know if any details needed.
Thanks,
Souvik

How to wait for the remote exe to complete - c#

The code looks lengthy but it's a simple program.
I have built a console app (TakeScreenshots) that will take website screenshots from firefox, chrome & ie in that order & save them in a folder. When I manually run TakeScreenshots.exe, all 3 screenshots are saved.
Now, I have built another console app (MyApp) that will execute TakeScreenshots.exe. But in this way, only the firefox screenshot is saved and not of the other 2. There are no exceptions. It just says "Process Complete". I guess, MyApp is not waiting for the TakeScreenshots to complete.
How can I fix this.
[TakeScreenshots will later be placed in few remote computers & run by MyApp]
TakeScreenshots code:
private static string[] WebDriversList = ["firefox","chrome","internetexplorer"];
private static void TakeAPic()
{
string url = "http://www.google.com";
string fileNamePrefix = "Test";
string snapSavePath = "D:\\Pics\\";
foreach (string wd in WebDriversList)
{
IWebDriver NewDriver = null;
switch (wd.ToLower())
{
case "firefox":
using (NewDriver = new FirefoxDriver())
{
if (NewDriver != null)
{
CaptureScreenshot(NewDriver, url, fileNamePrefix, snapSavePath);
}
}
break;
case "chrome":
using (NewDriver = new ChromeDriver(WebDriversPath))
{
if (NewDriver != null)
{
CaptureScreenshot(NewDriver, url, fileNamePrefix, snapSavePath);
}
}
break;
case "internetexplorer":
using (NewDriver = new InternetExplorerDriver(WebDriversPath))
{
if (NewDriver != null)
{
CaptureScreenshot(NewDriver, url, fileNamePrefix, snapSavePath);
}
}
break;
}
if (NewDriver != null)
{
NewDriver.Quit();
}
}
}
private static void CaptureScreenshot(IWebDriver driver,string url,string fileNamePrefix,
string snapSavePath)
{
driver.Navigate().GoToUrl(url);
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ICapabilities capabilities = ((RemoteWebDriver)driver).Capabilities;
ss.SaveAsFile(snapSavePath + fileNamePrefix + "_" + capabilities.BrowserName + ".png",
ImageFormat.Png);
}
MyApp code:
static void Main(string[] args)
{
ExecuteTakeScreenshot();
Console.WriteLine("PROCESS COMPLETE");
Console.ReadKey();
}
private static void ExecuteTakeScreenshot()
{
ProcessStartInfo Psi = new ProcessStartInfo("D:\\PsTools\\");
Psi.FileName = "D:\\PsTools\\PsExec.exe";
Psi.Arguments = "/C \\DESK101 D:\\Release\\TakeScreenshots.exe";
Psi.UseShellExecute = false;
Psi.RedirectStandardOutput = true;
Psi.RedirectStandardInput = true;
Process.Start(Psi).WaitForExit();
}
Update:
It was my mistake. Initially WebDriversPath was assigned "WebDrivers/". When I changed it to the actual path "D:\WebDrivers\", it worked. But I still dont understand how it worked when TakeScreenshots.exe was run manually and it doesn't when run from another console
In similar problems I have had success with waiting for input idle first. Like this:
Process process = Process.Start(Psi);
process.WaitForInputIdle();
process.WaitForExit();
You could try this. For me it was needed to print a pdf using Adobe Reader and not close it to early afterwards.
Example:
Process process = new Process();
process.StartInfo.FileName = DestinationFile;
process.StartInfo.Verb = "print";
process.Start();
// In case of Adobe Reader the following statement is needed:
process.WaitForInputIdle();
process.WaitForExit(2000);
process.WaitForInputIdle();
process.Kill();

Get path of current active window using window handle

I'd like to know how to grab the Path of the current active window using C#.
i get handle of currnet active window
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
now how do i get path of this window?
i.e: Path of "my document" window is
C:\Users\User\Documents
-=-=-==-=-=edit-=-=-=-=-=-
i want to wirte program to monitor "windows explorer" and see Where the user goes?
(i.e:user go to c:\ and then go to program files and then go to Internet Explorer and i want to get this path:C:\Program Files\Internet Explorer.
Add a reference (COM) to "Microsoft Internet Controls"
var explorer = new SHDocVw.ShellWindowsClass().Cast<SHDocVw.InternetExplorer>().Where(hwnd => hwnd.HWND == handle).FirstOrDefault();
if (explorer != null) {
string path = new Uri(explorer.LocationURL).LocalPath;
Console.WriteLine("name={0}, path={1}", explorer.LocationName, path);
}
Prints the title/path of the explorer.exe instance with the main window handle in handle.
use a thread...
Exception threadEccezione = null;
System.Threading.Thread staThread = new System.Threading.Thread(
delegate()
{
try
{
//SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
var explorer = new SHDocVw.ShellWindowsClass().Cast<SHDocVw.InternetExplorer>().Where(hwnd => hwnd.HWND == handle).FirstOrDefault();
if (explorer != null)
{
string path = new Uri(explorer.LocationURL).LocalPath;
MessageBox.Show(path);
}
}
catch (Exception ex)
{
threadEccezione = ex;
}
}
);
;
staThread.Start();
staThread.Join();

Categories