How to get a labels value in Selenium Chrome Driver using C# - c#

I am making a bot that list all the given assembled letters to make the players connect or build a word around that given value of assembled letters, im very new to selenium and still grasping the best practices thanks in advance. (https://jklm.fun "BombParty")
https://i.stack.imgur.com/wGyMd.png
What we want to achieve:
//locate the element (the one the center of that bomb)
//extract the elements displayed value (the label)
//Console Log that value
My Code:
ChromeOptions options = new ChromeOptions(); //creating chrome driver options to add some commands to remove the message "This is automated . . ."
options.AddAdditionalCapability("useAutomationExtension", true);
options.AddExcludedArgument("enable-automation");
options.AddArgument("window-size=1200x600");
var driver = new ChromeDriver(options); //declear our driver for us to automate and control
driver.Navigate().GoToUrl("https://jklm.fun/QVVC"); // go to our targeted uri
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(25); // wait for sometime to give our client to load
// let our user enter the username or join a game
while (true) // loop our funtion to locate and extract the given word
{
try
{
driver.FindElements(By.CssSelector("div.syllable")); //we did a FindElements because the label can change value over time and state another syllable
Console.WriteLine("Success!");
}
catch
{
Console.WriteLine("Failed!");
}
}
The Output of my Code:
Success!
What I Have tried:
var word = driver.FindElement(By.CssSelector("div.syllable"));
Console.WriteLine(word.Text.ToString());
The Result: Failed!
Update:
So i tried to get the value after it finds it and i will find it again,it was a success but it only returns this string, how to fix this?
The update

Related

How to select Options-Button on specifig page C# Selenium

I try to select an option of a Button and found a working solution ;)
But i did not understand why the mostly posted standard will not work.
My solution is this line:
webdriver.FindElement(By.XPath("//select[#id='select-max-bars']/option[contains(text(), '200 000')]")).Click();
What i want to do:
Side: https://eatradingacademy.com/software/forex-historical-data/
Scroll a little down and Navigate to "Settings" (blue Text).
Here the Button for "Maximum bars" must be changed to 200.000.
Why will the Code just down not work for this?
Can anybody explain this for me?
Thank you
Here are the Side-Elements:
enter image description here
This is my not working code. The last 5 lines are the problem:
// Start driver
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = false; // hide Console
webdriver = new ChromeDriver(service);
webdriver.Manage().Window.Maximize();
webdriver.Navigate().GoToUrl("https://eatradingacademy.com/software/forex-historical-data/");
Thread.Sleep(1000);
// deny upcoming Request
webdriver.FindElement(By.Id("webpushr-deny-button")).Click();
// Navigate to Page (Link) = Settings
webdriver.SwitchTo().Frame(webdriver.FindElement(By.Id("data-app-frame")));
var statistics = webdriver.FindElement(By.XPath("//a[#class='nav-link panel-switch' and contains(text(), 'Settings')]"));
Actions actions = new Actions(webdriver);
actions.MoveToElement(statistics);
actions.Perform();
statistics.Click();
// Click Button "Reset"
webdriver.FindElement(By.Id("btn-reset-settings")).Click();
// for Test only: Button can be clicked
// //webdriver.FindElement(By.Id("select-max-bars")).Click();
// How to select the Option in the "Drop Down" Button "Maximum Bars" ?
// This here will not work for me:
// ###################################################################
SelectElement objSelect = new SelectElement(webdriver.FindElement(By.Id("select-max-bars")));
Thread.Sleep(15);
//objSelect.selectByText("200 000");
objSelect.SelectByValue("200000");

Issue Logging in to TextNow using Selenium

I'm trying to automate TextNow using Selenium but when I add Username and password, I am getting an error "Username or Password is invalid". But, the same is working fine manually.
below is the code which i tried
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("cromepath");
driver.Url = "https://www.textnow.com/messaging";
driver.Manage().Window.Maximize();
IWebElement userName = driver.FindElement(By.Id("txt-username"));//txt-password
IWebElement password = driver.FindElement(By.Id("txt-password"));
userName.SendKeys("username");
password.SendKeys("password");
IWebElement login = driver.FindElement(By.Id("btn-login"));
login.Click();
}
You mentioned you get an error that username / password are invalid. Are you sure you are sending the right credentials?
Your XPath is correct here, so waiting for element to exist is most likely issue
-- textnow.com does take a minute to load. You might also want to clear both WebElements before sending keys.
using OpenQA.Selenium.Support.UI;
// declare wait of 15 seconds
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
// wait for element to exist, then store it in username variable
var username = wait.Until(drv => drv.FindElement(By.Id("txt-username")));
// clear & send keys
username.Clear();
username.SendKeys("username");
The same approach can be repeated for password.
If you are still getting username / password invalid, and you are sure you are using correct credentials, then it's possible SendKeys() is happening too quickly & keystrokes are not all registering in the input fields..
You can wrap SendKeys() in a method to slowly send keys, in case the input entering too quickly is a problem:
public static void SlowlySendKeys(this IWebElement element, string text)
{
// first clear element
element.Clear();
// slowly send keys, wait 100ms between each key stroke
foreach (var c in text) {
element.SendKeys(c);
System.Threading.Thread.Sleep(100);
}
}
Then, you can call:
username.SlowlySendKeys("username");
This will slow down key strokes and work around issue where key strokes are sent too quickly.

How to get whole Facebook friends list from api

Is there a way to get the whole Facebook friends list using an api!
I've tried a lot of thing and here's my shot:
FacebookClient f = new FacebookClient(access_token);
f.IsSecureConnection = true;
dynamic friendlist = await f.GetTaskAsync(#"https://graph.facebook.com/me/friendlists?access_token="+access_token);
t.Text = JsonConvert.SerializeObject(friendlist);
But all I got is an empty data!
Can anyone help me?
The friendlists endpoint is deprecated, as you can see in the breaking changes log: https://developers.facebook.com/docs/graph-api/changelog/breaking-changes#tagged-users-4-4
It would not have been what you expected anyway, it was only for lists, not friends directly. Access to all friends is not possible since a very long time. You can only get data of users/friends who authorized your App. You can use the /me/friends endpoint for that.
Another thread about getting all friends: Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application
There is another way can give you an access to your all friend list names by downloading a copy of your facebook information data by selecting friends and following checkbox and wait till your file is ready then download it.
This is not the API way but for starters who want one time download list of friends
Go to the friend list page: https://www.facebook.com/friends/list
Scroll all the way down so that all friend list loads
Press F12 to open developer tools, click on console tab
A. Show in console
copy paste following script in console and hit enter.
var accumulated = "";
for (var el of document.querySelectorAll('[data-visualcompletion="ignore-dynamic"]')) {
var name = el.getAttribute("aria-label");
if(name!= null && name != "null"){
accumulated = "Name:"+name +", "+ accumulated;
console.log(accumulated);
accumulated = "";
}else{
var a = el.getElementsByTagName("a")[0];
if(a){
accumulated += "Profile URL: "+ a.getAttribute("href");
//console.log(a);
}
}
}
B. Download a .json file
copy paste following script in console and hit enter.
var exportObj = [];
var accumulated = "";
for (var el of document.querySelectorAll('[data-visualcompletion="ignore-dynamic"]')) {
var name = el.getAttribute("aria-label");
if(name!= null && name != "null"){
exportObj.push({name: name, profileURL: accumulated});
accumulated = "";
}else{
var a = el.getElementsByTagName("a")[0];
if(a){
accumulated += a.getAttribute("href");
}
}
}
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "friendsList.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
Note: pseudo code tested in firefox

c# setting a printer

Hello and thank you for you time on this question, I'm trying change a Active Printer according to the choice that user chooses in excel. However I'm having some trouble. For some reason it keeps giving me the same error.
"An exception of type 'System.Runtime.InteropServices.COM Exception'
occurred in DailyReport.dll but was not handled in user code Exception
from HRESULT:0X800A03EC"
I've been goggling this error and im having a hard time finding anything, I did find a link COM Exception and they provided a link to another website but seems when I try to go that site it doesn't open.
I have Tried:
xlApp.ActivePrinter = "CORPPRT58-Copier Room on RR-PS1:";
xlApp.ActivePrinter = "\\RR-PS1\CORPPRT58-Copier Room";
xlApp.ActivePrinter = "CORPPRT58-Copier Room on RR-PS1";
I have checked to make sure that the printer is installed and it is. if someone could point me in the correct direction that would be great thanks!!
The correct answer is (i.e.):
xlApp.ActivePrinter = "\\\\RR-PS1\\CORPPRT58-Copier Room on Ne00:";
An important part is the 'Ne00:' This is the port on which this printer can be found. This is different on each computer and can be found in registry at HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices.
Another problem is the concatenation string 'on'. This may be valid when working with an English excel but it's translated to other languages!
I had the same problem but there aren't many complete examples I could find so here is mine:
// Open excel document
var path = #"c:\path\to\my\doc.xlsx";
Microsoft.Office.Interop.Excel.Application _xlApp;
Microsoft.Office.Interop.Excel.Workbook _xlBook;
_xlApp = new Microsoft.Office.Interop.Excel.Application();
_xlBook = _xlApp.Workbooks.Open(path);
_xlBook.Activate();
var printer = #"EPSON LQ-690 ESC/P2";
var port = String.Empty;
// Find correct printerport
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(path))
{
if (key != null)
{
object value = key.GetValue(printer);
if (value != null)
{
string[] values = value.ToString().Split(',');
if (values.Length >= 2) port = values[1];
}
}
}
// Set ActivePrinter if not already set
if (!_xlApp.ActivePrinter.StartsWith(printer))
{
// Get current concatenation string ('on' in enlgish, 'op' in dutch, etc..)
var split = _xlApp.ActivePrinter.Split(' ');
if (split.Length >= 3)
{
_xlApp.ActivePrinter = String.Format("{0} {1} {2}",
printer,
split[split.Length - 2],
port);
}
}
// Print document
_xlBook.PrintOutEx();
It's far for perfect since I'm not aware of any other translations. If 'on' is translated with spaces, above will fail. But i'm guessing that the solution will work for most clients. You can easily get the current concatenation string by looking at the currect value of ActivePrinter.
A more failproof method would be to strip the printer name and the assigned port and what remains is the concatenation string. But then you would have to loop through all installed printers and check for a match.
Another test I personally do it check if the printer is installed on the system:
if(PrinterSettings.InstalledPrinters.Cast<string>().ToList().Contains(printer)) {
//Set active printer...
}
First set your target printer as the default printer on the control pannel. Then print xlApp.ActivePrinter and get its settings(if you don't set the activeprinter the application gets the default setting of windows). At last set the value with the print value. And you can change your default printer setting.

How to keep browser open/reuse with Selenium?

I've looked extensively through Google and Stackoverflow, but i cant find a good way to implement keeping the browser open after a run and reuse it for the next run. I have it login, get text, but it closes after. I want to keep it open so I dont have relaunch the browser, login again and take more time than necessary. Simply want to use that same webpage, refresh/update the page, and get the new text(its dhtml). I have it to run every 10 seconds or so. Here what i have so far.
using (var driver = new ChromeDriver(""))
{
driver.Navigate().GoToUrl(#"");
// Get User Name field, Password field and Login Button
var userNameField = driver.FindElementByName("j_username");
var userPasswordField = driver.FindElementByName("j_password");
var loginButton = driver.FindElementByName("Submit");
// Type user name and password
userNameField.SendKeys("");
userPasswordField.SendKeys("");
// and click the login button
loginButton.Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.ClassName(""));
});
// Extract resulting message and save it into result.txt
string result = driver.FindElement(By.ClassName("")).Text;
}

Categories

Resources