---
# System prepended metadata

title: 訂票機器人 - a python guide

---

# 訂票機器人 - a python guide

## 你需要什麼
- scheduler/timer
    - 主動觸發
    - 定時觸發
- 網頁/伺服器互動方式
    - (難)直接透過API與後端伺服器互動 (HTTP)
        - 前提是你要知道API或是他有提供API讓你呼叫. 難度高
    - (簡單)透過模擬使用者對網頁元件的互動達成
        - python package: selenium

## 今天來嘗試
1. 安裝selenium
    - install selenium python package using pip 
        - `pip install selenium`
    - ~~download chrome webdriver~~
        - ~~https://chromedriver.chromium.org/downloads~~
    - install webdriver_manager
        - `pip install webdriver_manager`
2. 利用selenium做些簡單的元件控制
    - locating elements
        - https://selenium-python.readthedocs.io/locating-elements.html
        - `driver.find_element()`
    - element interaction
        - `send_keys()`
        - `click()`
## code
```python
# import some key objects in selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# import other libraries
import time

# open chrome 
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

# open chrome in incognito mode 
# chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument("--incognito")
# driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), chrome_options=chrome_options)


# open the website
driver.get("https://www.google.com")

# wait for the webpage to fully load
driver.implicitly_wait(10)

# input some text to the search bar
text = driver.find_element(By.NAME, 'q')
text.send_keys('hello')
# text.send_keys(Keys.ENTER)

# click the search button
search_button = driver.find_element(By.NAME, 'btnK')
print(search_button)
search_button.click()

# wait(optional) and quit
time.sleep(10)
driver.quit()

```

## reference
- selenium official docs (https://www.selenium.dev/documentation/)
- selenium api docs(https://www.selenium.dev/selenium/docs/api/py/api.html)
- preferable way to wait(https://www.selenium.dev/documentation/webdriver/waits/)
- https://tonidata.medium.com/%E8%87%AA%E5%8B%95%E6%90%B6%E7%A5%A8%E7%A8%8B%E5%BC%8F-%E7%94%A8python%E6%90%B6%E7%86%B1%E8%B3%A3%E5%95%86%E5%93%81-1f542f50c395
- http://blog.e-happy.com.tw/%E9%AB%98%E9%90%B5%E8%A8%82%E7%A5%A8%E9%AB%98%E6%89%8B%E7%A8%8B%E5%BC%8F%E4%BF%AE%E6%AD%A3/
- https://igouist.github.io/post/2020/03/bandon-1-selenium/
- https://www.learncodewithmike.com/2020/06/python-selenium-waits.html
- https://zcgnotes.com/pythonselenium%E4%B8%89%E7%A8%AE%E7%AD%89%E5%BE%85%E6%96%B9%E5%BC%8F/
- https://stackoverflow.com/questions/64717302/deprecationwarning-executable-path-has-been-deprecated-selenium-python