【发布时间】:2021-01-30 19:03:41
【问题描述】:
我想测试一个不是英文的网站,它有一些像äüöé 这样的字符。我得到一个包含以下代码的元素:
use strict;
use warnings;
use Selenium::Chrome;
use Selenium::Waiter qw/wait_until/;
use Encode::Detect::Detector;
my $chrome_driver_path = "chromedriver.exe";
my $driver;
my %settings = (
'binary' => $chrome_driver_path,
);
$driver = Selenium::Chrome->new(%settings);
$driver->get("website_with_utf");
my $element_id = 'my_element';
my $element;
$element = $driver->find_elements("//label[\@id='$element_id']"))[0];
if (defined($element)){
print ("element_id: '$element_id' found");
}else{
print ("element_id: '$element_id' could not be found");
return -1;
}
my $text = $element->get_text();
my $encoding_text = Encode::Detect::Detector::detect($option_text);
print "SELENIUM before enconding for *$option_text*: $encoding_text\n";
$text = encode('UTF-8', $text, Encode::FB_CROAK) if (defined($text));
$encoding_text = Encode::Detect::Detector::detect($option_text);
print "SELENIUM after enconding for *$option_text*: $encoding_text\n";
这会返回:
öaö 之前的 SELENIUM:
öaö 编码后的 SELENIUM:EUC-KR
我想让 get_text 返回一个 UTF-8 值,而不必每次都编写编码行并导入 econde 库。我尝试了许多使用 utf8 和 use utf8::all; 的组合,但没有成功。有没有更简洁的方法来解决这个问题?
【问题讨论】:
-
如果你想让模块返回不同的东西,你必须告诉它这样做(如果它提供了一种方法让你)。但是你甚至没有提到你正在使用什么模块。请根据需要提供一个最小的、可运行的问题演示。见minimal reproducible example。
-
否则,这些奇妙的东西叫做 subs 可以帮助我们避免重复一系列语句......
-
use utf8;告诉 Perl 源代码是使用 UTF-8 编码的。在这里没用。 -
use utf8:all;不会影响模块,至少不会直接影响。 -
@ikegami 我为所有 selenium 脚本添加了通用语句。我在问是否有可能以某种方式将 utf8 设置为 selenium 框架中的默认输出。