JavaScriptでテキスト形式のバイナリデータ(?)を取得して、Python側で変換して保存しています。
Seleniumの画像保存で情報を探すと、URLを取得してPython側からリクエスト投げたり、スクリーンショット機能を使ったりするものが多かった。
その場合、テスト中の端末からしか取得できないバイナリデータの保存に使えなかったので、別の方法を模索して行き着いた。
修正
- レスポンスのテキストデータをそのまま返却していたが、
0x00
のデータが消えてしまったのでjs側で配列にして返すように変更
ソース
import time
from selenium import webdriver
def save_binary(url, filepath):
js = """
var getBinaryResourceText = function(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
var filestream = req.responseText;
var bytes = [];
for (var i = 0; i < filestream.length; i++){
bytes[i] = filestream.charCodeAt(i) & 0xff;
}
return bytes;
}
"""
js += "return getBinaryResourceText(\"{url}\");".format(url=url)
data_bytes = driver.execute_script(js)
with open(filepath, 'wb') as bin_out:
bin_out.write(bytes(data_bytes))
capabilities = {
'chromeOptions': {
# 'androidPackage': 'com.android.chrome',
}
}
# WebDriverを取得
driver = webdriver.Remote('http://localhost:9515', capabilities)
# Googleのページを表示
driver.get('https://www.google.co.jp/')
# Googleのロゴ画像を取得
image_url = "https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"
# 画像を保存
save_binary(image_url, 'googlelogo.png')
driver.quit()