c# Selenium clicking the matching result - c#

I want to click on the video that matches the channel name according to the results after searching on youtube, but I do the channel match, but I can click the channel, not the video. i want Channel Name Or Url When it matches, its video is opened.
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
options.AddArgument("start-maximized");
options.AddArgument("disable-infobars");
options.AddArgument("--disable-extensions");
var driver = new ChromeDriver(chromeDriverService, options);
driver.Navigate().GoToUrl("https://www.youtube.com/");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(1500));
var elementsWithSearchID = wait.Until((driver) => driver.FindElements(By.Id("search")));
var search = elementsWithSearchID.Where(e => e.TagName == "input").FirstOrDefault();
search.SendKeys("Hello\n");
Thread.Sleep(2000);
IWebElement channel = driver.FindElement(By.XPath("//*[#id=\"text\"]/a[contains(#href, '/channel/UCV1Nlv5cOSB--hEjRVo4mUA')]"));
channel.Click();

I checked your code and run it, so you want to open video which match with your channel name, right?
so you need to first take the link which match with your channel name and after that put below code .
driver.FindElement(By.XPath("//a[#href='/watch?v=VKIiCOZ2Eo4']")).Click();
instead of
IWebElement channel = driver.FindElement(By.XPath("//*[#id=\"text\"]/a[contains(#href, '/channel/UCV1Nlv5cOSB--hEjRVo4mUA')]"));

Related

Download file from Button link to specific folder on C drive

I am scraping the web page and navigating to correct location, however as being a new to the whole c# world I am stuck with downloading pdf file.
Link is hiding behind this
var reportDownloadButton = driver.FindElementById("company_report_link");
It is something like: www.link.com/key/489498-654gjgh6-6g5h4jh/link.pdf
How to download the file to C:\temp\?
Here is my code:
using System.Linq;
using OpenQA.Selenium.Chrome;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
// Initialize the Chrome Driver // chromeOptions
using (var driver = new ChromeDriver(chromeOptions))
{
// Go to the home page
driver.Navigate().GoToUrl("www.link.com");
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
// Get the page elements
var userNameField = driver.FindElementById("loginForm:username");
var userPasswordField = driver.FindElementById("loginForm:password");
var loginButton = driver.FindElementById("loginForm:loginButton");
// Type user name and password
userNameField.SendKeys("username");
userPasswordField.SendKeys("password");
// and click the login button
loginButton.Click();
driver.Navigate().GoToUrl("www.link2.com");
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
var reportSearchField = driver.FindElementByClassName("form-control");
reportSearchField.SendKeys("Company");
var reportSearchButton = driver.FindElementById("search_filter_button");
reportSearchButton.Click();
var reportDownloadButton = driver.FindElementById("company_report_link");
reportDownloadButton.Click();
EDIT:
EDIT 2:
I am not the sharpest pen on Stackoverflow community yet. I don't understand how to do it with Selenium. I have done it with
var reportDownloadButton = driver.FindElementById("company_report_link");
var text = reportDownloadButton.GetAttribute("href");
// driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
WebClient client = new WebClient();
// Save the file to desktop for debugging
var desktop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
string fileName = desktop + "\\myfile.pdf";
client.DownloadFile(text, fileName);
However web page seems to be a little bit tricky. I am getting
System.Net.WebException: 'The remote server returned an error: (401)
Unauthorized.'
Debugger pointing at:
client.DownloadFile(text, fileName);
I think it should really simulate Right click and Save Link As, otherwise this download will not work. Also if I just click on button, it opens PDF in new Chrome tab.
EDIT3:
Should it be like this?
using System.Linq;
using OpenQA.Selenium.Chrome;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
// declare chrome options with prefs
var options = new ChromeOptionsWithPrefs();
options.AddArguments("headless"); // we add headless here
// declare prefs
options.prefs = new Dictionary<string, object>
{
{ "download.default_directory", downloadFilePath }
};
// declare driver with these options
//driver = new ChromeDriver(options); we don't need this because we already declare driver below.
// Initialize the Chrome Driver // chromeOptions
using (var driver = new ChromeDriver(options))
{
// Go to the home page
driver.Navigate().GoToUrl("www.link.com");
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
// Get the page elements
var userNameField = driver.FindElementById("loginForm:username");
var userPasswordField = driver.FindElementById("loginForm:password");
var loginButton = driver.FindElementById("loginForm:loginButton");
// Type user name and password
userNameField.SendKeys("username");
userPasswordField.SendKeys("password");
// and click the login button
loginButton.Click();
driver.Navigate().GoToUrl("www.link.com");
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
var reportSearchField = driver.FindElementByClassName("form-control");
reportSearchField.SendKeys("company");
var reportSearchButton = driver.FindElementById("search_filter_button");
reportSearchButton.Click();
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
driver.Navigate().GoToUrl("www.link.com");
// click the link to download
var reportDownloadButton = driver.FindElementById("company_report_link");
reportDownloadButton.Click();
// if clicking does not work, get href attribute and call GoToUrl() -- this may trigger download
var href = reportDownloadButton.GetAttribute("href");
driver.Navigate().GoToUrl(href);
}
}
}
}
}
You could try setting the download.default_directory Chrome driver preference:
// declare chrome options with prefs
var options = new ChromeOptionsWithPrefs();
// declare prefs
options.prefs = new Dictionary<string, object>
{
{ "download.default_directory", downloadFilePath }
};
// declare driver with these options
driver = new ChromeDriver(options);
// ... run your code here ...
// click the link to download
var reportDownloadButton = driver.FindElementById("company_report_link");
reportDownloadButton.Click();
// if clicking does not work, get href attribute and call GoToUrl() -- this may trigger download
var href = reportDownloadButton.GetAttribute("href");
driver.Navigate().GoToUrl(href);
If reportDownloadButton is a link that triggers a download, then the file should download to the filePath you have set in download.default_directory.
Neither of these threads are in C#, but they speak of a similar issue:
How to control the download of files with Selenium + Python bindings in Chrome
How to use chrome webdriver in selenium to download files in python?
You can use WebClient.DownloadFile for that.

Chrome driver block image extension freeze the page?

With the new Selenium.WebDriver.ChromeDriver.74.0.3729.6 update, the problem came out.
https://chrome.google.com/webstore/detail/block-image/pehaalcefcjfccdpbckoablngfkfgfgj?hl=tr
I'm trying to use the extension above.
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddExtensions(#Application.StartupPath.ToString() + #"\block-image.crx");
driver = new ChromeDriver(chromeDriverService, chromeOptions, TimeSpan.FromMinutes(10));
run the program. My result page remains "data :,". does not go to the page I want. different extensions have tried the same unfortunately.

Stop chromedriver console window from appearing, Selenium c#

I'm using Selenium and C#, headless chrome.
I'm new to C#, so this might be something obvious, but I've looked at other questions and seen to add:
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
I added that to my Start() and the window still pops up, here is my start method:
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
var option = new ChromeOptions();
option.AddArguments("--headless", "--no-sandbox", "--disable-web-security", "--disable-gpu", "--incognito", "--proxy-bypass-list=*", "--proxy-server='direct://'", "--log-level=3", "--hide-scrollbars");
driver = new ChromeDriver(option);
Please let me know if you need anything else, thank you in advance!
You are very nearly at the solution you want. You set the property on the service, but never used it anywhere. What you want is the following:
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
var option = new ChromeOptions();
option.AddArguments("--headless", "--no-sandbox", "--disable-web-security", "--disable-gpu", "--incognito", "--proxy-bypass-list=*", "--proxy-server='direct://'", "--log-level=3", "--hide-scrollbars");
driver = new ChromeDriver(chromeDriverService, options);

How to start ChromeDriver in headless mode

I want to try out headless chrome, but I am running into this issue, that I can't start the driver in headless mode. I was following google documentation. am I missing something ? The code execution gets stuck in var browser = new ChromeDriver(); line
Here is my code:
var chromeOptions = new ChromeOptions
{
BinaryLocation = #"C:\Users\2-as Aukstas\Documents\Visual Studio 2017\Projects\ChromeTest\ChromeTest\bin\Debug\chromedriver.exe",
DebuggerAddress = "localhost:9222"
};
chromeOptions.AddArguments(new List<string>() {"headless", "disable-gpu" });
var browser = new ChromeDriver(chromeOptions);
browser.Navigate().GoToUrl("https://stackoverflow.com/");
Console.WriteLine(browser.FindElement(By.CssSelector("#h-top-questions")).Text);
UPDATE
Chrome version 60 is out so all you need to do is to download Chromdriver and Selenium via Nuget and use this simple code and everything works like a charm. Amazing.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
...
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
using (var browser = new ChromeDriver(chromeOptions))
{
// add your code here
}
DATED
There is a solution until the official release of Chrome 60 will be released. You can download Chrome Canary and use headless with it. After installation set BinaryLocation to point to chrome canary also comment out the DebuggerAddress line(it forces chrome to timeout):
var chromeOptions = new ChromeOptions
{
BinaryLocation = #"C:\Users\2-as Aukstas\AppData\Local\Google\Chrome SxS\Application\chrome.exe",
//DebuggerAddress = "127.0.0.1:9222"
};
chromeOptions.AddArguments(new List<string>() { "no-sandbox", "headless", "disable-gpu" });
var _driver = new ChromeDriver(chromeOptions);
For you that did not get reference for ChromeDriver.
Use this step :
Download the dll from this: http://seleniumtestings.com/selenium-download/
Extract, and you should see: Selenium.WebDriverBackedSelenium.dll, ThoughtWorks.Selenium.Core.dll, WebDriver.dll and WebDriver.Support.dll
Add those files via "Add Reference"
Now you can use it:
String url = "http://www.google.com";
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(new List<string>() {
"--silent-launch",
"--no-startup-window",
"no-sandbox",
"headless",});
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true; // This is to hidden the console.
ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
driver.Navigate().GoToUrl(url);
====
If after you run, you are still facing error about no ChromeDriver.exe file, try to add the Selenium.WebDriver.ChromeDriver, WebDriver.ChromeDriver, WebDriver.ChromeDriver.win32, Selenium.Chrome.WebDriver via nuget.
As alternative:
Add 2 libraries via NuGet like below picture.
Try below Code:
String url = "http://www.google.com";
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(new List<string>() { "headless" });
var chromeDriverService = ChromeDriverService.CreateDefaultService();
ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
driver.Navigate().GoToUrl(url);
What OS you're running? I see on developers.google.com/web/updates/2017/04/headless-chrome that headless won't be available on Windows until Chrome 60.
Below i have given how to set the headless to true for firefox and chrome browsers.
FirefoxOptions ffopt = new FirefoxOptions();
FirefoxOptions option = ffopt.setHeadless(true);
WebDriver driver = new FirefoxDriver(option);
ChromeOptions coptions = new ChromeOptions();
ChromeOptions options = coptions.setHeadless(true);
WebDriver driver = new ChromeDriver(options);

Selenium webdriver with Dynamic Crm online

Trying to use the webdriver to do some automated testing with crm. Im having issues with consistency. Ill run a test and it'll pass and the next time it will fail.I tried using waits and am still having this isuse. Has anyone used crm and selenium together and know any ideas on how to fix this issue?
IWebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
// Thread.Sleep(10000);
driver.Navigate().GoToUrl("https://login.microsoftonline.com/ea791863-b17d-43ec-90ba-148d3fa0a86f/wsfed?wa=wsignin1.0&wtrealm=https%3a%2f%2fmerlintest.crm.dynamics.com%2f&wctx=pr%3dwsfederation%26rm%3dhttps%253a%252f%252fmerlintest.crm.dynamics.com%252f%26ry%3dhttps%253a%252f%252fmerlintest.crm.dynamics.com%252fmain.aspx&wct=2017-07-05T20%3a42%3a50Z&wreply=https%3a%2f%2fcloudredirector.crm.dynamics.com%3a443%2fG%2fAuthRedirect%2fIndex.aspx%3fRedirectTo%3dhttps%253a%252f%252fmerlintest.crm.dynamics.com%252fmain.aspx#386670653");
IWebElement emailOrPhone = driver.FindElement(By.Id("cred_userid_inputtext")); //email or phone input
IWebElement password = driver.FindElement(By.Id("cred_password_inputtext"));//password input
emailOrPhone.SendKeys("email");
password.SendKeys("password");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("cred_sign_in_button")));
IWebElement enterButton = driver.FindElement(By.Id("cred_sign_in_button"));
enterButton.SendKeys(Keys.Enter);//login
driver.SwitchTo().DefaultContent();//switches frames ,needed this so we can grab elements
Thread.Sleep(5000);
//navigate to search box and enter candidate name
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementExists((By.ClassName("navImageFlipHorizontal"))));
driver.FindElement(By.ClassName("navImageFlipHorizontal")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
Thread.Sleep(5000);
driver.FindElement(By.Id("navTabButtonSearchD365Id")).SendKeys("");
driver.FindElement(By.Id("findCriteriaImg")).Click();
WebDriverWait iwait = new WebDriverWait(driver, TimeSpan.FromSeconds(25));
IWebElement element = iwait.Until(
ExpectedConditions.ElementIsVisible(By.Id("searchTextBox")));
Thread.Sleep(5000);
driver.FindElement(By.Id("searchTextBox")).Clear();
driver.FindElement(By.Id("searchTextBox")).SendKeys("lisa steinburg");
driver.FindElement(By.Id("searchTextBox")).SendKeys(Keys.Enter);

Categories

Resources