LoginSignup
8
7

More than 5 years have passed since last update.

pythonでchromeを起動させる

Last updated at Posted at 2017-03-27

※他サイトのコンテンツをクローリングしてきて、ちょっとだけ変えて、あたかもオリジナルのように振舞う、そんな悪質なクローリングはやってはだめ、ぜったい

pythonでクローリングのプログラムを書く場合は、下記のような感じ。
※今回は試しでGoogleで適当な検索ワードを使って検索する方法

今回はchromeを使うので事前に

から環境に合わせたドライバーをDLし、格納しておく必要がある。
※下記ではオプションでDL先の指定をしているが、必要ない場合ははずしてもOK
※エラーとかでうまくdriverを閉じれないとどんどんバックグラウンドで走るchrome.exeが増えていってメモリを圧迫するので、簡単なエラー処理入れといたほうが良い。

from selenium import webdriver
import time
import traceback

try:
    dl_folder_path = "ファイルをDLするときのパス"
    chromedriver = "ドライバーの格納パス"
    search_text = "検索ワード"
    prefs = {
        "download.default_directory": dl_folder_path}
    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_experimental_option("prefs", prefs)
    # chromeを起動しサイトへ移動
    driver = webdriver.Chrome(chromedriver, chrome_options=chromeOptions)
    driver.get(
        "https://www.google.co.jp/")
    time.sleep(2)
    # 検索窓の取得
    serachBox = driver.find_element_by_name("q")
    # 検索ワードの入力
    serachBox.send_keys(search_text)
except Exception as e:
    print(traceback.format_exc())
    driver.close()
    driver.quit()
8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7