まだ使い熟せていないですが・・・ | python3Xのブログ

python3Xのブログ

ここでは40代、50代の方が日々の生活で役に立つ情報や私の趣味であるプログラム、Excelや科学に関する内容で投稿する予定です。

Google Chrome のwebdriverを使ってスクレイピングしたいと思い

その準備段階です

以前のPhantomJSだと、そう難しくないことが

Chromeだと上手くいかなかったり

取り敢えず、今回はその下準備です

 

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
# オプションを作成
options = Options()
# Google Chrome Canaryのパスを指定
options.binary_location = 'C:/Users/nakano/AppData/Local/Chromium/chrome.exe'
# ヘッドレスブラウザ指定
options.add_argument('--headless')
driver = webdriver.Chrome()
# Googleを開いてみる
driver.get('https://www.google.co.jp')
# タイトルにGoogleが含まれているのを確認
assert 'Google' in driver.title
# 検索窓を取得
input_elem = driver.find_element_by_name('q')
# キーワードを入力
input_elem.send_keys('Deep learning')
# 検索
input_elem.send_keys(Keys.RETURN)
# 画面切り替わりを待つため適当な時間待つ
time.sleep(2)
assert 'Deep learning' in driver.title
# スクリーンショットを撮る。
driver.save_screenshot('ss.png')
# 検索結果のタイトルとURLを表示する。
for a in driver.find_elements_by_css_selector('h3 > a'):
    print(a.text)
    print(a.get_attribute('href'))
# ブラウザを終了
driver.quit()