pythonでselenium環境構築でハマったのでメモ。
てかheadlessなったり、動きが激しいので古い記事は役立たず、公式ページをみるが正。
いやー しかしseleniumはブラウザ間の依存がひどい。。
環境
mac os
python3.5
結論
ドライバーをダウンロードしてある場所にコピる必要あり。そのパスをコード実行時に指定するのだ。
下の内容には惑わされず、ここから最新とってください。
https://www.seleniumhq.org/download/
Selenium Client & WebDriver Language BindingsのPythonバージョンを取得。
sudo pip install selenium
wget https://github.com/mozilla/geckodriver/releases/download/v0.19.0/geckodriver-v0.19.0-macos.tar.gz
#展開して/usr/local/binにコピー
wget https://chromedriver.storage.googleapis.com/2.32/chromedriver_mac64.zip
#展開して/usr/local/binにコピー
import time
from selenium import webdriver
driver = webdriver.Chrome('/usr/local/bin/chromedriver') # Optional argument, if not specified will search path.
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()
で実行。
ローカルのファイルを実行した場合
getするときに file:// を前につけて 絶対パスにするとうまくいった。
htmlのデータセットを大量に作ってスクリーンショットを撮りまくりたかったのでこんな雰囲気で使った。
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
class capturer():
def take(self, file_name):
options = Options()
options.add_argument("--headless")
options.add_argument("--disable-infobars")
browser = webdriver.Chrome(chrome_options=options, executable_path="/usr/local/bin/chromedriver")
browser.get('file:///Users/hoge_user/hoge_tool/'+file_name+".html")
browser.save_screenshot(file_name+".png")
browser.close()
cap = capturer()
cap.take('hoge')
エラー1
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
geckodriver
https://github.com/mozilla/geckodriver/releases
参考
http://pc.atsuhiro-me.net/entry/2017/01/15/124308
エラー2
selenium.common.exceptions.WebDriverException: Message: unknown error: Runtime.executionContextCreated has invalid 'context'
brewではダメなんだと言われた。
brew uninstall --force chromedriver
直でダウンロードしてbinにコピーしたらいけた
https://chromedriver.storage.googleapis.com/index.html?path=2.32/
Selenium API(逆引き)
http://www.seleniumqref.com/api/webdriver_gyaku.html
PythonでSeleniumを操作する
https://kurozumi.github.io/selenium-python/index.html
言語ごとのselenium
https://yizeng.me/2014/02/23/how-to-get-window-size-resize-or-maximize-window-using-selenium-webdriver/#python-example