Selenium with Python で webdriver 使った習作その1

Yahoo!の検索結果から画像検索のURLのみ抽出

#!/usr/bin/env python
# coding=utf-8

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.yahoo.co.jp/")

# 検索実行
search_word = u"夏目"
search_box = driver.find_element_by_id("srchtxt")
search_box.send_keys(search_word)

button=driver.find_element_by_id("srchbtn")
button.click()

# 結果確認
# aタグのリスト作成
aList = driver.find_elements_by_tag_name("a")
for a in aList:

 # href が画像検索なものに絞り込み
 if  a.get_attribute("href"):
  if a.get_attribute("href").find("http://image.search.yahoo.co.jp/search") >=0:

   # imgタグのsrcを出力
   for img in a.find_elements_by_tag_name("img"):
    print img.get_attribute("src")

# ブラウザ閉じる
driver.close()

# ネストが深くてXPathで書くのが面倒で....