Chromedriver:如何使用硒翻译页面?

时间:2018-12-11 04:34:34

标签: selenium selenium-chromedriver google-translate translate

我需要在chrome浏览器中使用硒将页面从日语翻译为英语。我尝试了以下示例代码段之一的不同方式

animation

我尝试了几种解决方法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(); } } options.addArguments,但是没有任何效果可以建议我什么解决方法

2 个答案:

答案 0 :(得分:3)

您需要启用翻译功能并将目标语言ID添加到白名单{"from" : "to"}

"translate":{"enabled":"true"}
"translate_whitelists": {"ja":"en"}

在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);

答案 1 :(得分:0)

这里是C#版本,直接在“AddUserProfilePreference”中添加“translate”和“translate_whitelists”

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);