selenium change language浏览器chrome/firefox

2024-05-26 16:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用selenium测试我的网站,但我没有设法更改浏览器的语言。我试过使用firefox,也更改了配置文件,但它不起作用。

很遗憾,因为我的很多内容在语言方面都在改变。

这是我的python代码:

@classmethod
def setUpClass(cls):
    super(SeleniumTestCase, cls).setUpClass()
    options = Options()
    options.add_argument('--lang=en')
    cls.selenium = WebDriver(chrome_options=options)

所以通常我会改变语言但什么也没发生。。

提前谢谢!

只是想澄清一下。我已经检查了stackoverflow,如果我发布这个问题,那是因为我尝试了我看到的大多数解决方案。


Tags: 代码语言内容网站def配置文件selenium浏览器
3条回答

答案已经在最近的一篇文章中找到:
Change language on Firefox with Selenium Python

代码如下:

def get_webdriver(attempts=3, timeout=60, locale='en-us'):
  firefox_profile = webdriver.FirefoxProfile()
  firefox_profile.set_preference("intl.accept_languages", locale)
  firefox_profile.update_preferences()

  desired_capabilities = getattr(
      DesiredCapabilities, "FIREFOX").copy()

  hub_url = urljoin('http://hub:4444', '/wd/hub')
  driver = webdriver.Remote(
    command_executor=hub_url, desired_capabilities=desired_capabilities,
    browser_profile=firefox_profile)

  return driver

此代码适用于在本地计算机上运行浏览器的最简单用例。

对于火狐:

from selenium import webdriver

browser_locale = 'fr'
gecko_driver_path = 'geckodriver64.exe'

profile = webdriver.FirefoxProfile()
profile.set_preference('intl.accept_languages', browser_locale)

browser = webdriver.Firefox(executable_path=gecko_driver_path,
                            firefox_profile=profile)
browser.get('https://google.com/')

对于铬:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

browser_locale = 'fr'
chrome_driver_path = 'chromedriver.exe'

options = Options()
options.add_argument("--lang={}".format(browser_locale))

browser = webdriver.Chrome(executable_path=chrome_driver_path,
                           chrome_options=options)
browser.get('https://google.com/')

我有这个java代码,请用python修改它

使用Firefox浏览器:

FirefoxProfile profile = new FirefoxProfile();
//setting the locale french : ‘fr’
profile.setPreference(“intl.accept_languages”,”fr”);
driver = new FirefoxDriver(profile);
driver.get(“http://google.co.in);

使用Chrome浏览器:

System.setProperty(“webdriver.chrome.driver”,”D:/DollarArchive/chromedriver.exe”);
ChromeOptions options = new ChromeOptions();
options.addArguments(“–lang= sl”);
ChromeDriver driver = new ChromeDriver(options);
driver.get(“http://google.co.in);

在python中设置如下内容

对于firefox

driver.set_preference(“intl.accept_languages”,”fr”)

铬合金

options.add_argument(“–lang= sl”)

希望对你有帮助:)

相关问题 更多 >

    热门问题