Selenium Webdriver-设置首选的浏览器语言DE

时间:2018-08-30 13:54:03

标签: ruby selenium selenium-webdriver webdriver

使用Selenium Webdriver和Ruby在无头Chrome中设置首选语言(接受的语言)时出现问题。我使用以下WebDriver设置:

[{ [Number: 2155085824
   value: 2155085824,
   description: 'The value supplied for the attribute is not of the same type as the attribute\'s value.',
name: 'BadTypeMidmatch' }]
[]

然后使用以下命令初始化驱动程序:

Selenium::WebDriver::Chrome.driver_path = @config[<path to the Chrome Driver>]

options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless')
options.add_argument('--disable-translate')
options.add_argument("--lang=de")

一切正常,但在某些页面上,即使我导航至德语页面的网址(例如page.de),Chrome也会返回英语内容。在这些情况下,由于内部转发至page.de/en,Chrome驱动程序会返回英语内容。我未在查询的URL中指定en路径。

我尝试使用Webdriver首选项设置语言:

@selenium_driver = Selenium::WebDriver.for :chrome, options: options

代替add_argument,但它不会改变任何行为。

有没有人知道如何在Ruby中强制由Selenium Webdriver控制的无头Chrome浏览器以定义的语言请求页面内容,或者-不是最佳方法,但可以作为一种解决方法-停止转发?

任何帮助表示赞赏

最佳

克里德

5 个答案:

答案 0 :(得分:0)

我正在test_helper.rb中使用它,对我来说很好。

Capybara.register_driver :selenium do |app|
  Chromedriver.set_version "2.36"

  desired_capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
    'chromeOptions' => {
      'prefs' => {
        'intl.accept_languages' => 'en-US'
     },
     args: ['disable-gpu', 'headless']
   }
  )

  Capybara::Selenium::Driver.new(app, { browser: :chrome, desired_capabilities: desired_capabilities })
end

Capybara.javascript_driver = :chrome
Capybara.default_driver = :selenium

答案 1 :(得分:0)

您应该可以通过添加实验选项来解决您的问题:

options.add_option('prefs', {'intl.accept_languages': 'en,en_US'})

我确定它可以在Python上使用,但是我还没有在Ruby上尝试过:这种方法是正确的,不确定实现方式。
您可以在this repository中找到处理您的Python代码问题的代码,并在this Q&A中找到如何在Ruby中实现experimental_options

答案 2 :(得分:0)

我找到了适合我的解决方案。在许多情况下,问题出在屏幕前,根本无法满足您的要求;-)

代替使用

options.add_argument("--lang=de")

您必须使用

options.add_argument("--lang=de-DE")

当我使用IETF语言标签时,我最初发布的代码可以正常工作。

答案 3 :(得分:0)

为我工作:

import {useSelector,useDispatch} from 'react-redux;

const dispatch=useDispatch();
const stateSelector=useSelector(state=>({
    your states
}));

答案 4 :(得分:0)

prefs 哈希中的这个 options 哈希对我有用。它位于 driven_by :selenium 行的末尾。

(内部 test/application_syste_test_case.rb

# frozen_string_literal: true

require 'test_helper'
require 'capybara/rails'

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :chrome, screen_size: [1400, 1400], options: { prefs: { 'intl.accept_languages' => 'de,de-DE;q=0.9,en;q=0.1' } }

# ...

2021-06-14 更新:

上一个示例产生此弃用警告:

WARN Selenium [DEPRECATION] :prefs is deprecated. Use Selenium::WebDriver::Chrome::Options#add_preference instead.

IMO,下面的解决方案更丑陋,但我会在它完全弃用且原始版本停止工作时发布它。

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by(:selenium,
    using: :chrome,
    screen_size: [1400, 1400],
    options: {
      options: Selenium::WebDriver::Chrome::Options.new(
        prefs: { 'intl.accept_languages' => 'de,de-DE;q=0.9,en;q=0.1' }
      )
    },
  )

相关问题