Selenium commands not working in Chrome web driver (working with firefox) - selenium

I'm writing integration/e2e tests and for some reason any selenium driver commands don't see to be working with chromedriver, but they are working flawlessly with firefox driver and the firefox headless driver.
Commands tried: moveByOffset, and doubleClick
Tried both Geb's Interact method
interact {
doubleClick(centerClickable)
}
and accessing the webdriver directly:
def driver = browser.getDriver()
Actions action = new Actions(driver)
WebElement element= driver.findElement(By.className("vis-drag-center"))
def doubleclick = action.doubleClick(element).build()
doubleclick.perform()
Both methods work with the firefox driver. Neither work with chrome driver.
GebConfig.groovy file is set up as thus:
import io.github.bonigarcia.wdm.WebDriverManager
import org.openqa.selenium.Dimension
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.firefox.FirefoxOptions
def chromeWebDriverVersion = '70.0.3538.67'
def driverFirefox = {
WebDriverManager.firefoxdriver().setup()
def driver = new FirefoxDriver()
driver.manage().window().setSize(new Dimension(width, height))
return driver
}
// ChromeDriver reference: https://sites.google.com/a/chromium.org/chromedriver/
// Download and configure ChromeDriver using https://github.com/bonigarcia/webdrivermanager
def driverChrome = {
WebDriverManager.chromedriver().version(chromeWebDriverVersion).setup()
def driver = new ChromeDriver()
driver.manage().window().setSize(new Dimension(width, height))
return driver
}
environments {
firefox {
driver = driverFirefox
}
chrome {
driver = driverChrome
}
//driver = driverFirefox
driver = driverChrome
I also tried version 2.43 of chrome.
Additional information:
Mac Mojave
Selenium v 3.7.0
geb v 2.2
spockcore v 1.1-groovy-2.4
groovy v 2.4.5
webdrivermanager v 3.0.0
If anyone is interested, what the test is doing: Selecting a vis.js element by clicking on it. Sleeping for a second (code not included here), then opening/activating it by double clicking it. Or dragging it.
Apart from the selenium actions everything works fine with chromedriver and geb. It's only now that I need the doubleClick and moveByOffset (not move to an element!) that I'm getting issues getting things to work properly
I found a similar question on here, might be the same issue. Maybe not. But there's no solution provided: Selenium Web Driver DragAndDropToOffset in Chrome not working?
Any help is hugely appreciated.

Thank you for your response kriegaex.
Your tests work for me as well. This leads me to think there's just some lower-level interaction between differences in how selenium's chromedriver and firefox driver have implemented the doubleclick and dragAndDropBy actions + the way our application responds to commands.
For any other people observing similar behaviour, I use a work-around where I add an additional action for chromedriver. Perhaps it's nicer to actually find out which KEYDOWN events etc. you should be using and fire those, or perhaps find out why application isn't responding to these events. But I feel like enough time is spent on this already :)
if (browser.getDriver().toString().contains("chrome")) {
// Work-around for chromedriver's double-click implementation
content.click()
}
interact {
doubleClick(content)
}
And for the dragAndDropBy:
def drag(Navigator content, int xOff, int yOff) {
//Work-around: move additional time for when chrome driver is used.
int timesToMove = browser.getDriver().toString().contains("chrome") ? 2 : 1
interact {
clickAndHold(content)
timesToMove.times {
moveByOffset(xOff, yOff)
}
release()
}
}

I just had a little bit of time and was curious because I never tried to perform a double-click in any of my tests before. So I used this page as a test case and ran the following test with both Firefox and Chrome drivers:
package de.scrum_master.stackoverflow
import geb.spock.GebReportingSpec
import org.openqa.selenium.By
import org.openqa.selenium.interactions.Actions
class DoubleClickTest extends GebReportingSpec {
def "double-click via Geb interaction"() {
given:
go "https://demo.guru99.com/test/simple_context_menu.html"
def doubleClickButton = $("button", text: "Double-Click Me To See Alert")
expect:
withAlert {
interact {
doubleClick(doubleClickButton)
}
} == "You double clicked me.. Thank You.."
}
def "double-click via Selenium action"() {
given:
go "https://demo.guru99.com/test/simple_context_menu.html"
def doubleClickButton = driver.findElement(By.tagName("button"))
def doubleClick = new Actions(driver).doubleClick(doubleClickButton).build()
expect:
withAlert {
doubleClick.perform()
} == "You double clicked me.. Thank You.."
}
}
It works flawlessly, both ways of double-clicking trigger the expected Javascript alert.
I am not even using the latest driver version 2.45 but 2.41 against Chrome 71 64-bit on Windows 10. Besides, I also use bonigarcia's Webdriver Manager. I have no idea what is wrong with your setup. My Selenium version is 3.14.0, a bit newer than yours, Geb 2.2, Spock 1.1-groovy-2.4, Groovy 2.4.7.
Maybe it is a MacOS thing? I cannot verify that. Maybe you just run my test first, then maybe upgrade your Selenium and if that also does not help try to downgrade the Chrome driver in order to find out if the problem could be driver version related.
Update: I upgraded to Chrome driver 2.45, the test still works.
Update 2022-02-16: Updated the test to work with another example page, because the old URL still exists, but the Javascript there no longer works.

Related

Download file through Google Chrome RemoteWebDriver- headless mode in Linux using Selenium Java [duplicate]

I'm do me code in Cromedrive in 'normal' mode and works fine. When I change to headless mode it don't download the file. I already try the code I found alround internet, but didn't work.
chrome_options = Options()
chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'{}/chromedriver'.format(os.getcwd()))
self.driver.set_window_size(1024, 768)
self.driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': os.getcwd()}}
self.driver.execute("send_command", params)
Anyone have any idea about how solve this problem?
PS: I don't need to use Chomedrive necessarily. If it works in another drive it's fine for me.
First the solution
Minimum Prerequisites:
Selenium client version: Selenium v3.141.59
Chrome version: Chrome v77.0
ChromeDriver version: ChromeDriver v77.0
To download the file clicking on the element with text as Download Data within this website you can use the following solution:
Code Block:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--window-size=1920,1080")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args=["--log-path=./Logs/DubiousDan.log"])
print ("Headless Chrome Initialized")
params = {'behavior': 'allow', 'downloadPath': r'C:\Users\Debanjan.B\Downloads'}
driver.execute_cdp_cmd('Page.setDownloadBehavior', params)
driver.get("https://www.mockaroo.com/")
driver.execute_script("scroll(0, 250)");
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#download"))).click()
print ("Download button clicked")
#driver.quit()
Console Output:
Headless Chrome Initialized
Download button clicked
File Downloading snapshot:
Details
Downloading files through Headless Chromium was one of the most sought functionality since Headless Chrome was introduced.
Since then there were different work-arounds published by different contributors and some of them are:
Downloading with chrome headless and selenium
Python equivalent of a given wget command
Now the, the good news is Chromium team have officially announced the arrival of the functionality Downloading file through Headless Chromium.
In the discussion Headless mode doesn't save file downloads #eseckler mentioned:
Downloads in headless work a little differently. There's the Page.setDownloadBehavior devtools command to set a download folder. We're working on a way to use DevTools network interception to stream the downloaded file via DevTools as well.
A detailed discussion can be found at Issue 696481: Headless mode doesn't save file downloads
Finally, #bugdroid revision seems to have nailed the issue for us.
[ChromeDriver] Added support for headless mode to download files
Previously, Chromedriver running in headless mode would not properly download files due to the fact it sparsely parses the preference file given to it. Engineers from the headless chrome team recommended using DevTools's "Page.setDownloadBehavior" to fix this. This changelist implements this fix. Downloaded files default to the current directory and can be set using download_dir when instantiating a chromedriver instance. Also added tests to ensure proper download functionality.
Here is the revision and commit
From ChromeDriver v77.0.3865.40 (2019-08-20) release notes:
Resolved issue 2454: Headless mode doesn't save file downloads [Pri-2]
Solution
Update ChromeDriver to latest ChromeDriver v77.0 level.
Update Chrome to Chrome Version 77.0 level. (as per ChromeDriver v76.0 release notes)
Note: Chrome v77.0 is yet to be GAed/pushed for release so till then you can download and install a development build and test either from:
Chrome Canary
Latest build from the Dev Channel
Outro
However Mac OSX users have a wait for their pie as On Chromedriver, headless chrome crashes after sending Page.setDownloadBehavior on MacOSX.
Chomedriver Version: 95.0.4638.54
Chrome Version 95.0.4638.69
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--start-maximized")
options.add_argument("--no-sandbox")
options.add_argument("--disable-extensions")
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
options.add_argument('--disable-software-rasterizer')
options.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166")
options.add_argument("--disable-notifications")
options.add_experimental_option("prefs", {
"download.default_directory": "C:\\link\\to\\folder",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing_for_trusted_sources_enabled": False,
"safebrowsing.enabled": False
}
)
What seemed to work was that I used "\\" instead of "/" for the address. The latter approach didn't throw any error, but didn't download any documents either. But, using double back slashes did the job.
For javascript use below code:
const chrome = require('selenium-webdriver/chrome');
let options = new chrome.Options();
options.addArguments('--headless --window-size=1500,1200');
options.setUserPreferences({ 'plugins.always_open_pdf_externally': true,
"profile.default_content_settings.popups": 0,
"download.default_directory": Download_File_Path });
driver = await new webdriver.Builder().setChromeOptions(options).forBrowser('chrome').build();
Then switch tabs as soon as you click the download button:
await driver.sleep(1000);
var Handle = await driver.getAllWindowHandles();
await driver.switchTo().window(Handle[1]);
This C# works for me
Note the new headless option https://www.selenium.dev/blog/2023/headless-is-going-away/
private IWebDriver StartBrowserChromeHeadlessDriver()
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--headless=new");
chromeOptions.AddArgument("--window-size=1920,1080");
chromeOptions.AddUserProfilePreference("download.default_directory", downloadFolder);
var chromeDownload = new Dictionary<string, object>
{
{ "behavior", "allow" },
{ "downloadPath", downloadFolder }
};
var driver = new ChromeDriver(driverFolder, chromeOptions, TimeSpan.FromSeconds(timeoutSecs));
driver.ExecuteCdpCommand("Browser.setDownloadBehavior", chromeDownload);
return driver;
}
import pathlib
from selenium.webdriver import Chrome
driver = Chrome()
driver.execute_cdp_cmd("Page.setDownloadBehavior", {
"behavior": "allow",
"downloadPath": str(pathlib.Path.home().joinpath("Downloads"))
})
I don't think you should be using the browser for downloading content, leave it to Chrome developers/testers.
I believe you should rather get href attribute of the element you want to download and obtain it using requests library
If your site requires authentication you could fetch cookies from the browser instance and pass them to requests.Session.

Selenium Chromedriver opens with data:, in navigation bar

if i open Chrome via chromedriver and navigate to a URL i only get a data:, in the navigation bar. All googled solutions (right chromedriverversion, protocoll in URL, etc.) didnt help me.
package de.vhv.selenium;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class OpenChromeAndNavigate {
#Test
public void test() {
System.setProperty("webdriver.chrome.driver", "C://vhventw//selenium//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.de");
}
}
In addition everything works if i add --headless and listen to the debugport. But i dont want to let it run headless.
package de.vhv.selenium;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class OpenChromeAndNavigate {
#Test
public void test() {
System.setProperty("webdriver.chrome.driver", "C://vhventw//selenium//chromedriver.exe");
WebDriver driver = new ChromeDriver(getDesiredCapabilities());
driver.get("https://www.google.de");
}
private ChromeOptions getDesiredCapabilities() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
// options.addArguments("--disable-extensions"); // disabling extensions
// options.addArguments("--disable-gpu"); // applicable to windows os only
// options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
// options.addArguments("--no-sandbox");
options.addArguments("--remote-debugging-port=9223");
return options;
}
}
Any ideas what i can try?
Setup:
Chrome Version = 71.0.3578.80
Chromedriver Version = 2.46.628402
I figured out, that the line
options.addArguments("--remote-debugging-port=9225");
fixed my problem. I already used it in headless runs to listen to the port and watch the headless run. But it fixed my problem with headfull runs.
return new ChromeDriver(getDesiredCapabilities());
private ChromeOptions getDesiredCapabilities() {
ChromeOptions options = new ChromeOptions();
//options.addArguments("--headless");
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox");
options.addArguments("--remote-debugging-port=9225");
return options;
}
You need to take care of a couple of things:
Not sure about your project structure but I will suggest to avoid the . character and the word selenium within the package name as in:
package de.vhv.selenium;
The Value part passed through System.setProperty() line containing the absolute path of chromedriver.exe should be expressed through escaped backslashes as:
System.setProperty("webdriver.chrome.driver", "C:\\vhventw\\selenium\\chromedriver.exe");
As per ChromeDriver - WebDriver for Chrome:
If you are using Chrome version 72, please download ChromeDriver 2.46 or ChromeDriver 72.0.3626.69
As per best practices:
Upgrade JDK to recent levels JDK 8u202.
Upgrade Selenium to current levels Version 3.141.59.
Upgrade ChromeDriver to current ChromeDriver v73.0.3683.68 level.
Keep Chrome version between Chrome v73 levels. (as per ChromeDriver v73.0.3683.68 release notes)
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.
Take a System Reboot.
Execute your #Test.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.
I was struggling with the same issue, then I realised that I forgot to start the test with :
$I->amOnPage('/');
definitely to try before digging deeper.

IE browser gets shrunk during execution

I am facing an weird issue. I have a selenium suite to execute on multiple browsers. It works fine of chrome and Firefox. But in case of IE, the web page under test gets shrunk (web page resize) making elements hidden. Hence facing NoSuchElementException.
I have already tried executing on full screen. No help.
Please help in solving this issue.
Thanks,
Praveen
Don't know the exact reason for that, however, suggested workaround would be to implement pre-execution method for your test which would take care of all your browser different configurations. For example, if you are using Java with Selenium and JUnit5, it might be:
#BeforeEach
void beforeTestExecution() {
DesiredCapabilities desiredCapabilities = DesiredCapabilities.internetExplorer();
desiredCapabilities.setCapability(
CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
driver = new InternetExplorerDriver(desiredCapabilities);
// Navigate to URL
driver.get("http://www.yoursite.com");
// Maximize your website window before test.
driver.manage().window().maximize();
}
Or:
#BeforeEach
void configBrowser() {
DesiredCapabilities desiredCapabilities = DesiredCapabilities.internetExplorer();
desiredCapabilities.setCapability(
CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
driver = new InternetExplorerDriver(desiredCapabilities);
// Start Internet Explorer maximized.
driver.manage().window().maximize();
}

Test work properly on Chrome, not on Firefox

I wrote test using TestNG and selenium.
code...
actions.sendKeys(Keys.chord(Keys.CONTROL, "a"));
actions.sendKeys(Keys.BACK_SPACE);
actions.build().perform();
code...
I wanted to delete text in login window using these sendKeys, with DataProvider
#DataProvider(name = "inputs")
public Object[][] getData() {
return new Object[][]{
{"000000000", true},
{"000000000", true}
};
}
Html:
<div><input type="tel" class="valid TextInput-kJdagG iVdKHC" name="recoveryPhone" id="eb69ff0b-3427-6986-7556-b7af40ffb156" aria-describedby="eb69ff0b-3427-6986-7556-b7af40ffb156" value="+48 "></div>
Error message:
Unable to read VR
Path1523545392670 Marionette INFO Enabled via --marionette
1523545393744 Marionette INFO Listening on port 52644
1523545394180 Marionette WARN TLS certificate errors will be ignored for this session
Test work as I expected on Chrome, but on firefox these sendKeys not always mark the text, and clear this text. In project I have to use action class. Why the test runs differently?
Check this post https://github.com/mozilla/geckodriver/issues/665 against your versions (browser, browser driver, selenium etc which are always sensible to include in any question), it could be a known bug with the geckodriver.
The post includes a work around of creating the chord in a different way, using:
List<CharSequence> keyWithModifiers = new ArrayList<CharSequence>();
keyWithModifiers.add(Keys.CONTROL);
keyWithModifiers.add("a");
String ctrlA = Keys.chord(keyWithModifiers);
textFieldElem.sendKeys(ctrlA);
This approach worked for me using Selenium 3.7.1 Java bindings, gecko driver 0.18.0 (64 bit) and Firefox 57.0.2 - 59.0

Getting an error with 2.26 and 2.27 Selenium release while creating an Augmenter

When I create the Augmenter (see below) with 2.25 release of Selenium, it used to work fine. With 2.26 and 2.27 I'm getting the following error. Could you please suggest what extra is needed with a 2.26+ release to get things working again?
I get the following error:
java.lang.IllegalAccessException-->Class org.openqa.selenium.remote.Augmenter$CompoundHandler can not access a member of class org.openqa.selenium.firefox.FirefoxDriver with modifiers "protected"Exception caught starting Firefox webdriver
The relevant code:
WebDriver driver = new FirefoxDriver();
WebDriver augmentedDriver = new Augmenter().augment(driver);
Since newer release of selenium Agumenter only works for the RemoteWebDriver.
It was never really supported, but now is also doesn't work
Which feature you need the Agumenter for?
I.e. to take a screenshot you can make make a direct cast of the FriefoxDriver:
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
To initialize a mixed hub/local driver:
if (useHub) {
...
webDriver = new RemoteWebDriver(hubURL, desiredCapabilities);
webDriver = new Augmenter().augment(webDriver);
} else {
switch(webDriverType) {
case Type.FIREFOX:
webDriver = new FirefoxDriver();
}
}
then use webDriver as normal