我正在嘗試編寫檢查佈局問題的Selenium測試。爲此,我使用Java端的Selenium Webdriver和phantomjs作爲「瀏覽器」。我想使用phantomjs,因爲它可以製作實際渲染組件的屏幕截圖。如何使用webdriver(Java)在phantomjs上禁用字體消除鋸齒?
默認情況下,phantomjs使用反鋸齒呈現文本,這使得很難掃描文本(以查找文本基線並執行簡單的OCR)。
我該如何告訴phantomJS不要使用抗鋸齒?
我正在嘗試編寫檢查佈局問題的Selenium測試。爲此,我使用Java端的Selenium Webdriver和phantomjs作爲「瀏覽器」。我想使用phantomjs,因爲它可以製作實際渲染組件的屏幕截圖。如何使用webdriver(Java)在phantomjs上禁用字體消除鋸齒?
默認情況下,phantomjs使用反鋸齒呈現文本,這使得很難掃描文本(以查找文本基線並執行簡單的OCR)。
我該如何告訴phantomJS不要使用抗鋸齒?
我使用了下面的詭計來禁用Linux上的phantomjs反鋸齒。 PhantomJS是使用fontconfig構建的,該庫在多個位置查找文件「fonts.conf」:請參閱https://www.freedesktop.org/software/fontconfig/fontconfig-user.html。
通過創建以下fonts.conf我們可以爲禁用的fontconfig抗鋸齒:
<match target="font">
<edit mode="assign" name="antialias">
<bool>false</bool>
</edit>
</match>
其中一個位置由環境變量定義,根據規格:$ XDG_CONFIG_HOME/fontconfig的/ fonts.conf 。因此,通過使用上述內容創建一個像/tmp/phantomjs-config/fontconfig/fonts.conf這樣的臨時文件,然後將XDG_CONFIG_HOME設置爲/ tmp/phantomjs-config,我們可以通過fontconfig來讀取該文件。
雖然有一個問題:默認情況下,PhantomJSDriver類不允許設置環境變量。這很令人傷心,因爲底層工作者代碼PhantomWebDriverService確實允許這樣做。
爲了解決這個我創建了我複製從PhantomJSDriverService一些保護方法,一個小的輔助類:
public class MyPhantomDriverService {
public static PhantomJSDriverService createDefaultService(Capabilities desiredCapabilities, Map<String, String> env) {
Proxy proxy = null;
if (desiredCapabilities != null) {
proxy = Proxy.extractFrom(desiredCapabilities);
}
File phantomjsfile = findPhantomJS(desiredCapabilities, "https://github.com/ariya/phantomjs/wiki", "http://phantomjs.org/download.html");
File ghostDriverfile = findGhostDriver(desiredCapabilities, "https://github.com/detro/ghostdriver/blob/master/README.md", "https://github.com/detro/ghostdriver/downloads");
Builder builder = new Builder();
builder.usingPhantomJSExecutable(phantomjsfile)
.usingGhostDriver(ghostDriverfile)
.usingAnyFreePort()
.withProxy(proxy)
.withLogFile(new File("phantomjsdriver.log"))
.usingCommandLineArguments(findCLIArgumentsFromCaps(desiredCapabilities, "phantomjs.cli.args"))
.usingGhostDriverCommandLineArguments(findCLIArgumentsFromCaps(desiredCapabilities, "phantomjs.ghostdriver.cli.args"));
if(null != env)
builder.withEnvironment(env);
return builder.build();
}
public static File findPhantomJS(Capabilities desiredCapabilities, String docsLink, String downloadLink) {
String phantomjspath;
if (desiredCapabilities != null && desiredCapabilities.getCapability("phantomjs.binary.path") != null) {
phantomjspath = (String)desiredCapabilities.getCapability("phantomjs.binary.path");
} else {
phantomjspath = (new ExecutableFinder()).find("phantomjs");
phantomjspath = System.getProperty("phantomjs.binary.path", phantomjspath);
}
Preconditions.checkState(phantomjspath != null, "The path to the driver executable must be set by the %s capability/system property/PATH variable; for more information, see %s. The latest version can be downloaded from %s", "phantomjs.binary.path", docsLink, downloadLink);
File phantomjs = new File(phantomjspath);
checkExecutable(phantomjs);
return phantomjs;
}
protected static File findGhostDriver(Capabilities desiredCapabilities, String docsLink, String downloadLink) {
String ghostdriverpath;
if (desiredCapabilities != null && desiredCapabilities.getCapability("phantomjs.ghostdriver.path") != null) {
ghostdriverpath = (String)desiredCapabilities.getCapability("phantomjs.ghostdriver.path");
} else {
ghostdriverpath = System.getProperty("phantomjs.ghostdriver.path");
}
if (ghostdriverpath != null) {
File ghostdriver = new File(ghostdriverpath);
Preconditions.checkState(ghostdriver.exists(), "The GhostDriver does not exist: %s", ghostdriver.getAbsolutePath());
Preconditions.checkState(ghostdriver.isFile(), "The GhostDriver is a directory: %s", ghostdriver.getAbsolutePath());
Preconditions.checkState(ghostdriver.canRead(), "The GhostDriver is not a readable file: %s", ghostdriver.getAbsolutePath());
return ghostdriver;
} else {
return null;
}
}
protected static void checkExecutable(File exe) {
Preconditions.checkState(exe.exists(), "The driver executable does not exist: %s", exe.getAbsolutePath());
Preconditions.checkState(!exe.isDirectory(), "The driver executable is a directory: %s", exe.getAbsolutePath());
Preconditions.checkState(exe.canExecute(), "The driver is not executable: %s", exe.getAbsolutePath());
}
private static String[] findCLIArgumentsFromCaps(Capabilities desiredCapabilities, String capabilityName) {
if (desiredCapabilities != null) {
Object cap = desiredCapabilities.getCapability(capabilityName);
if (cap != null) {
if (cap instanceof String[]) {
return (String[])((String[])cap);
}
if (cap instanceof Collection) {
try {
Collection<String> capCollection = (Collection<String>)cap;
return (String[])capCollection.toArray(new String[capCollection.size()]);
} catch (Exception var4) {
System.err.println(String.format("Unable to set Capability '%s' as it was neither a String[] or a Collection<String>", capabilityName));
}
}
}
}
return new String[0];
}
}
有了這個新代碼,我現在可以創建一個PhantomJSDriver如下:
//-- 1. Make a temp directory which will contain our fonts.conf
String tmp = System.getProperty("java.io.tmpdir");
if(tmp == null) {
tmp = "/tmp";
}
File dir = new File(tmp + File.separator + "/_phantomjs-config/fontconfig");
dir.mkdirs();
if(! dir.exists()) {
throw new IOException("Can't create fontconfig directory to override phantomjs font settings at " + dir);
}
File conf = new File(dir, "fonts.conf");
String text = "<match target=\"font\">\n"
+ "<edit mode=\"assign\" name=\"antialias\">\n"
+ "<bool>false</bool>\n"
+ "</edit>\n"
+ "</match>";
try(FileOutputStream fos = new FileOutputStream(conf)) {
fos.write(text.getBytes("UTF-8"));
}
//-- Set the XDG_CONFIG_HOME envvar; this is used by fontconfig as one of its locations
Map<String, String> env = new HashMap<>();
env.put("XDG_CONFIG_HOME", dir.getParentFile().getAbsolutePath());
PhantomJSDriverService service = MyPhantomDriverService.createDefaultService(capabilities, env);
wd = new PhantomJSDriver(service, capabilities);
此代碼最重要的問題是,如果有fonts.conf文件(如$ HOME/.fonts.conf),它可能會失敗在定義反鋸齒。但對於我的測試用例來說,這工作正常。
要禁用無頭鉻抗鋸齒使用上述相同的代碼來生成fonts.conf文件,然後如下分配一個鍍鉻的webdriver:
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeDriverService.Builder;
...
Map<String, String> env = new HashMap<>();
env.put("XDG_CONFIG_HOME", dir.getParentFile().getAbsolutePath());
Builder builder = new Builder();
builder.usingAnyFreePort();
builder.withEnvironment(env);
ChromeDriverService service = builder.build();
return new ChromeDriver(service, dc);
我建議你開始遠離它。現在它不再支持。 https://groups.google.com/forum/#!topic/phantomjs/9aI5d-LDuNE –
我知道,但人們仍在使用它。過渡到別的不是很快;) – fjalvingh
實際上,同樣的技巧也適用於無頭Chrome;)我也會更新答案。 – fjalvingh