# -*- coding: utf-8 -*-
#!/usr/bin/python

from bs4 import BeautifulSoup
#import selenium
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

#driver = selenium.webdriver.Firefox()
driver = webdriver.Firefox()
driver.implicitly_wait(10)  # 隐性等待和显性等待可以同时用，但要注意：等待的最长时间取两者之中的大者
driver.maximize_window()  # 最大化

driver.get('https://www.google.com')

print('name: %s' % (driver.name))
print('title: %s' % (driver.title))
print('url: %s' % (driver.current_url))
#print(driver.page_source)

# 找到輸入框
#element = driver.find_element(By.NAME, 'q')
element = driver.find_element_by_name('q')

# 輸入內容
element.send_keys('張金順 視障')
# 提交表單
#element.send_keys(Keys.ENTER)
element.submit()

print('title2: %s' % (driver.title))
print('url2: %s' % (driver.current_url))

#time.sleep(10)
try:
   wait = WebDriverWait(driver, 10)
#   element = wait.until(EC.title_contains('張金順'))
   #locator = (By.TAG_NAME, 'h3')
   #locator = (By.CLASS_NAME, 'LC20lb')
   locator = (By.CSS_SELECTOR, 'h3.LC20lb')
   #locator = (By.XPATH, '//h3[@class="LC20lb"]')
   #element = wait.until(EC.element_to_be_clickable(locator))
   element = wait.until(EC.presence_of_element_located(locator))

   print('title3: %s' % (driver.title))
   print('url3: %s' % (driver.current_url))
except TimeoutException:
   print('time out!')
#finally:
#   driver.quit()  # 完全釋放

soup = BeautifulSoup(driver.page_source, 'html.parser')
a = soup.find_all('a')
for s in a:
   break
   h = s.find('h3', class_='LC20lb')
   if h != None:
      print('----------')
      print(h.text)
      print(s.get('href'))

input('Press Enter to Continue......')
driver.quit()  # 完全釋放
