LoginSignup
15
26

More than 3 years have passed since last update.

Pythonでseleniumを用いたスクレイピング

Last updated at Posted at 2019-03-05

pythonにてseleniumを使う機会があったので、メモ。

chromedriverのダウンロード

以下のURLからchromedriverをダウンロード
http://chromedriver.chromium.org/downloads
firefoxdriverもあるらしい。

ライブラリの追加

➜   pip install selenium

無事インストールできたらOK

スクリプトでseleniumとchrome driverを読み込む

from selenium import webdriver
driver = webdriver.Chrome(executable_path="./chromedriver")

chromedriverへのパスは注意。上記コードは同じディレクトリに配置想定。

所定のURLのページを開く

url  = "https://www.google.co.jp/"
driver.get(url)

要素を取得する

以下の2つのメソッドを使用した。

  • find_elements_by_xpath
    • リストなど、複数あるものを取得。
    • ループを回してリストに繰り返し処理をかけて処理を効率化することができる。
  • find_element_by_xpath
    • 特定の要素を狙って取得

なお、xpath 以外にも、

  • id名
  • class名
  • その他

などの要素取得方法がある。
参考

今回は xpath を使用した。xapthはデベロッパーツールから確認できる。
macのショートカットは、 command + option + i

デベロッパーツールにて、HTML要素を右クリックするとメニューが出てくるので、
Copy > Copy XPath の順で選択。

スクリーンショット 2019-03-05 21.31.27.png

要素の中の属性を取得したい場合

要素(HTMLタグ)の中の属性(attribute)を取得したい場合は get_attribute("属性名") を使う。

driver.find_element_by_xpath("//div[@class='hoge']/div[1]/a/img").get_attribute("src")

例では src 属性の値を取得している。

取りたい要素にidやclassが割り振られておらず、同じタグが子要素として並んでいる場合

以下のような場合に b を取得するにはどうしたらいいか?

<div id="hoge">
  <div>a</div>
  <div>b</div>
  <div>c</div>
</div?>

以下のようにする。

driver.find_element_by_xpath("//div[@id='hoge']/div[2]").text

2番目に格納されているdivと明示的に示せば、bが取得できる。
参考

15
26
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
15
26