【Python】Google検索結果は非同期のためSeleniumでGoogleの検索結果のタイトルを取得するときはWait機能を使わないと正しいタイトルが取得できない
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from selenium import webdriver | |
from selenium.webdriver.common.keys import Keys | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.support.ui import WebDriverWait | |
from selenium.webdriver.support import expected_conditions as EC | |
# Firefox起動 | |
driver = webdriver.Firefox() | |
# googleへ | |
driver.get("https://www.google.co.jp") | |
while True: | |
# 標準入力の値を取得 | |
keyword = raw_input() | |
# 入力フォームの値をクリアにする | |
driver.find_element_by_name("q").clear() | |
# 入力フォームの要素を探す | |
element = driver.find_element_by_name("q") | |
# 入力フォームにキーワードを入力する | |
element.send_keys(keyword) | |
# フォームを送信する | |
element.send_keys(Keys.RETURN) | |
# titleタグに標準入力したキーワードが含まれるまで10秒待つ | |
WebDriverWait(driver, 10).until( | |
EC.title_contains(keyword) | |
) | |
# タイトル表示 | |
print driver.title | |
driver.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment