先回の続き。
操作対象のWebブラウザーをChromeからPhantomJSに変える。
PhantomJSはGUIを持たない、いわば透明なブラウザー。
これにしてやると、動作中に画面を占領されないし
コマンドラインから起動できてサーバー上でのバッチ実行などにも使えるようになる。
PhantomJSインストール
http://phantomjs.org/download.html からダウンロードしてパスを通しておく。
操作用Pythonスクリプトの作成
先回とほぼ同じ。
webdriverの作成の部分だけ変わる。
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import time from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By WAIT_SECOND = 30 USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36" if __name__ == '__main__': driver = webdriver.PhantomJS( service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'], desired_capabilities={'phantomjs.page.settings.userAgent': USER_AGENT}) driver.set_window_size(1280, 1024) driver.get('https://google.co.jp/') # 検索キーワードとエンターキーを入力 t=driver.find_element_by_id('lst-ib') t.send_keys(u'てけとーぶろぐ\n') # 要素の表示待ち WebDriverWait(driver, WAIT_SECOND).until( EC.visibility_of_element_located((By.CLASS_NAME, '_Rm'))) # リンクをクリック b=driver.find_element_by_xpath('//*[@id="rso"]/div/div/div[1]/div/div/h3/a') b.click() # 要素の表示待ち WebDriverWait(driver, WAIT_SECOND).until( EC.visibility_of_element_located((By.CLASS_NAME, 'entry-title-link'))) # スクリーンショットの保存 driver.save_screenshot("ss.png") # ソースの書き出し file_name = 'test.html' with codecs.open(file_name, 'a', 'utf_8') as f: f.write(driver.page_source) driver.close()