language translation in Selenium java - selenium

I am Trying to translate the webpage with following code but it did not work.
WebDriverManager.chromedriver().setup();
ChromeOptions option = new ChromeOptions();
option.addArguments("start-maximized");
option.addArguments("test-type");
option.addArguments("--lang=en-US");
option.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
option.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(option);
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.get("https://www.staffers.no/jobbsoker");

You can try with below code :
ChromeOptions option = new ChromeOptions();
option.addArguments("start-maximized");
option.addArguments("test-type");
option.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
option.setExperimentalOption("useAutomationExtension", true);
Map<String, Object> prefs = new HashMap<String, Object>();
Map<String, Object> langs = new HashMap<String, Object>();
langs.put("no", "en");
prefs.put("translate", "{'enabled' : true}");
prefs.put("translate_whitelists", langs);
option.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(option);
driver.get("https://www.staffers.no/jobbsoker");

Related

java.lang.IllegalArgumentException:Last character in replacement string can't be \, character to be escaped is required

i am using sikuli with selenium WebDriver previously it was working fine but now its throwin exception java.lang.ExceptionInInitializerError
getting exception on this line Screen sc =new Screen();
please help me
i have set envirnoment variable for sikuli and Using sikuli 1.1.0
public class RoleChangerInav {
WebDriver driver;
#Test
public void rolechanger()
{
try {
System.setProperty("webdriver.ie.driver","D:\\CoxWorkspace\\iNAVieProject\\IEDriverServer_Win32_2.52.0\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("nativeEvents", false);
ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept");
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
ieCapabilities.setCapability("disable-popup-blocking", true);
ieCapabilities.setCapability("enablePersistentHover", true);
ieCapabilities.setCapability("ignoreZoomSetting", true);
ieCapabilities.setCapability("introduceInstabilityByIgnoringProtectedModeSettings", true);
ieCapabilities.setCapability("ie.ensureCleanSession", true);
ieCapabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
ieCapabilities.setJavascriptEnabled(true);
//ieCapabilities.setPlatform(org.openqa.selenium.Platform.WIN10);
ieCapabilities.setCapability("introduceInstabilityByIgnoringProtectedModeSettings", true);
ieCapabilities.setCapability("ie.ensureCleanSession", true);
ieCapabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
driver = new InternetExplorerDriver();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("URL");
driver.manage().window().maximize();
driver.findElement(By.linkText("More information")).click();
driver.navigate ().to ("javascript:document.getElementById('overridelink').click()");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
System.setProperty("webdriver.ie.driver","IEDriverServer.exe");
//Thread.sleep(2000);
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
WebElement userName = driver.findElement(By.name("j_username"));
userName.sendKeys("888888");
System.out.println("Username : 888888");
WebElement passWord = driver.findElement(By.name("j_password"));
passWord.sendKeys("*******");
System.out.println("Password : ********");
WebElement submit = driver.findElement(By.id("jadLoginBtn"));
submit.click();
Alert alert = driver.switchTo().alert();
alert.accept();
Thread.sleep(12000);
Screen sc =new Screen();
Pattern clicksite=new Pattern("click_site.png");
sc.wait(clicksite,2000);
sc.click();

Chromedriver: How to translate a page using selenium?

I need to translate a page from Japanese to English, using selenium in chrome browser. I tried different ways one of sample code snippet is as following
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Main {
private WebDriver driver=null;
WebDriverLoad a;
#Test
public void successfulDesignerLogin() throws Exception{
// final DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// capabilities.setJavascriptEnabled(true);
String chromedriver = "/dev/Saved/chromedriver";
System.setProperty("webdriver.chrome.driver",chromedriver);
ChromeOptions options = new ChromeOptions();
options.addArguments("--lang=en-ca");
//Map<String, Object> prefs = new HashMap<String, Object>();
//prefs.put("intl.accept_languages", "en,en_US");
//options.setExperimentalOption("prefs", prefs);
ChromeDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.get("https://www.bbc.com/japanese");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.close();
}
}
I tried a couple of solution options.addArguments options.setExperimentalOption but nothing works can any one suggests me what can be the solution
You need to enable translate and add target language ID to the whitelist {"from" : "to"}.
"translate":{"enabled":"true"}
"translate_whitelists": {"ja":"en"}
in java:
Map<String, Object> prefs = new HashMap<String, Object>();
Map<String, Object> langs = new HashMap<String, Object>();
langs.put("ja", "en");
prefs.put("translate", "{'enabled' : true}");
prefs.put("translate_whitelists", langs);
options.setExperimentalOption("prefs", prefs);
Here is a C# version, directly add "translate" and "translate_whitelists" in "AddUserProfilePreference"
ChromeOptions options = new ChromeOptions();
Dictionary<string, object> LanguageList = new Dictionary<string, object>();
LanguageList.Add("fr", "en");
Dictionary<string, bool> enableObject = new Dictionary<string, bool>();
enableObj.Add("enabled", true);
options.AddUserProfilePreference("translate", enableObject);
options.AddUserProfilePreference("translate_whitelists", LanguageList);

How to handle 'Keep' and 'Discard' option while download files in chrome in selenium without AutoIt?

I am using selenium ver. 2.47 and Chrome Ver. 70
I have tried with below code but it didn't worked.
Map<String, Object> prefs = new HashMap<String, Object>();
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
options.addArguments("--safebrowsing-disable-download-protection");
prefs.put("safebrowsing.enabled", "false");
Thanks
Seems you were pretty close. You need to pass the HashMap containing the required configurations to the instance of the ChromeOptions Class as follows:
System.setProperty("webdriver.chrome.driver", "C:/chromedriver/chromedriver.exe");
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("safebrowsing.enabled", "true"); //this is the needed configuration
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);

With Selenium 3.8.1, Firefox, Chrome, and IE driver capabilities are deprecated.

Can anybody advise how to remove warnings from FirefoxDriver (capabilities) and
ChromeDriver (capabilities)?
FIREFOX
{
#Override
public DesiredCapabilities getDesiredCapabilities ()
{
DesiredCapabilities capabilities = DesiredCapabilities.firefox ();
return capabilities;
}
#Override
public WebDriver getWebDriverObject (DesiredCapabilities capabilities)
{
return new FirefoxDriver (capabilities);
}
},
CHROME_Original
{
#Override
public DesiredCapabilities getDesiredCapabilities ()
{
DesiredCapabilities capabilities = DesiredCapabilities.chrome ();
capabilities.setCapability ("chrome.switches", Arrays.asList ("--no-default-browser-check"));
HashMap<String, String> chromePreferences = new HashMap<String, String> ();
chromePreferences.put ("profile.password_manager_enabled", "false");
capabilities.setCapability ("chrome.prefs", chromePreferences);
return capabilities;
}
#Override
public WebDriver getWebDriverObject (DesiredCapabilities capabilities)
{
return new ChromeDriver (capabilities);
}
},
Try to use the following code:
ChromeOptions options = new ChromeOptions();
options.setCapability("chrome.switches",Arrays.asList("--no-default-browser-check"));
HashMap<String, Boolean>chromePreferences = new HashMap<>();
chromePreferences.put("profile.password_manager_enabled", false);
options.setCapability("chrome.prefs", chromePreferences);
ChromeDriver driver = new ChromeDriver(options);
The ChromeDriver constructor now takes in ChromeOptions object as a parameter
Manipulating DesiredCapabilities directly has been deprecated in favor of type-safe “Options” classes (FirefoxOptions InternetExplorerOptions, etc). This has the advantage of helping you avoid setting incorrect or invalid values for the driver. You get rid of the deprecation warnings by changing your code to use the newer, safer construct.

Chromium/Chrome headless - file download not working?

I downloaded the latest version of chromium, to test out the headless feature.
When I run (as root, because I'm still testing things):
./chrome --no-sandbox http://cp7.awardspace.com/speed-test/awardspace-data1mb.zip
In the GUI terminal, it opens Chromium and downloads the file.
If I'm trying to run it headless, I enter the following:
./chrome --no-sandbox --headless http://cp7.awardspace.com/speed-test/awardspace-data1mb.zip
The terminal outputs some information, no window gets opened, but also: I don't have the file downloaded anywhere.
I have been scouting the internet and discussion groups for more information, but cannot find anything.
Is file downloading not working in headless mode for Chromium?
That's a reported bug in headless implementation:
https://bugs.chromium.org/p/chromium/issues/detail?id=696481
Use ChromeDriverService and POST session/{sessionId}/chromium/send_command
JSON for POST:
{
"cmd": "Page.setDownloadBehavior",
"params": {
"behavior": "allow",
"downloadPath": "C:\\Download\\Path"
}
}
C# Solution
Add reference to System.Net.Http and use NuGet to install Newtonsoft.JSON.
public static IWebDriver Driver { get; private set; }
public void SetDriver()
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("--headless", "--window-size=1920,1080");
var driverService = ChromeDriverService.CreateDefaultService();
Driver = new ChromeDriver(driverService, chromeOptions);
Task.Run(() => AllowHeadlessDownload(driverService));
}
static async Task AllowHeadlessDownload(ChromeDriverService driverService )
{
var jsonContent = new JObject(
new JProperty("cmd", "Page.setDownloadBehavior"),
new JProperty("params",
new JObject(new JObject(
new JProperty("behavior", "allow"),
new JProperty("downloadPath", #"C:\Download\Path")))));
var content = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");
var sessionIdProperty = typeof(ChromeDriver).GetProperty("SessionId");
var sessionId = sessionIdProperty.GetValue(Driver, null) as SessionId;
using (var client = new HttpClient())
{
client.BaseAddress = driverService.ServiceUrl;
var result = await client.PostAsync("session/" + sessionId.ToString() + "/chromium/send_command", content);
var resultContent = await result.Content.ReadAsStringAsync();
}
}
In Java use following code :
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--headless");
options.addArguments("--disable-extensions"); //to disable browser extension popup
ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver driver = new ChromeDriver(driverService, options);
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", "//home//vaibhav//Desktop");
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
httpClient.execute(request);
driver.get("http://www.seleniumhq.org/download/");
driver.findElement(By.linkText("32 bit Windows IE")).click();
The following code works in C# using ChromeDriver 2.46
private ChromeDriver GetDriver()
{
var options = new ChromeOptions();
options.AddArguments("headless");
options.AddUserProfilePreference("download.prompt_for_download", "false");
options.AddUserProfilePreference("download.directory_upgrade", "true");
options.AddUserProfilePreference("download.prompt_for_download", "false");
options.AddUserProfilePreference("safebrowsing.enabled", "false");
options.AddUserProfilePreference("safebrowsing.disable_download_protection", "true");
options.AddArguments("--disable-web-security");
var curr = Directory.GetCurrentDirectory();
options.AddUserProfilePreference("download.default_directory", curr);
var driver = new ChromeDriver(options);
Log.Info($"Started Chrome Driver with options: {options.ToJsonNoTypes()}");
var param = new Dictionary<string, object>();
param.Add("behavior", "allow");
param.Add("downloadPath", curr);
driver.ExecuteChromeCommand("Page.setDownloadBehavior", param);
return driver;
}
Note: Not exactly answer to the question, but solves the problem
I researched a lot on making headless chrome download with different parameters/options/preferences, but nothing worked. Then I used standard Java way of downloading file using Apache Commons's FileUtils
FileUtils.copyURLToFile(URI, FILE);
I was able to download files with chrome headless thanks to Chrome Remote Interface
public void TryEnableFileDownloading(string downloadPath)
{
TrySendCommand("Page.setDownloadBehavior", new Dictionary<string, object>()
{
["behavior"] = "allow",
["downloadPath"] = downloadPath
});
}
Full code for integration with selenium could be found here
https://github.com/cezarypiatek/Tellurium/blob/master/Src/MvcPages/SeleniumUtils/ChromeRemoteInterface/ChromeRemoteInterface.cs
More info about setDownloadBehavior and Chrome Remote interface
https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-setDownloadBehavior
I tried today in IdeaJ editor, Java and Maven on Windows 10, and it's working fine:
ChromeOptions ds = getDesiredCapabilities(browserName);
ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver driver = new ChromeDriver(driverService, ds);
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", System.getProperty("user.home") + File.separator + "Downloads");
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
httpClient.execute(request);
User this configured "driver" instance to navigate to download file either by URL or by Json/AngularJs download action.
Also it sometimes behaved to corrupt file while downloading due to internet slowness.
More on this, same configuration will work for both Google Chrome UI or Headless execution in latest chrome driver 77~