# 【學習筆記】Python使用Selenium(一):環境架設 開發環境 1.Windows 2.IDE:VSCode 3.python版本:3.11.3(2023/5/27目前最新版) ※ VSCode應該都會裝 ## Step1 下載python 安裝python 1.至python官網下載 網址:https://www.python.org/ 2.  3.  ※安裝時記得將Add Python XX.XXto PATH打勾 4.裝好之後去以下路徑找ptyhon安裝位置 C:\Users\XXX(使用者名稱)\AppData\Local\Programs\Python\Python311(看你裝什麼版本) 5.要確認有沒有裝好可以在cmd輸入以下指令看看 ``` python --version ``` 如果有回復Python x.xxx.x(版本編號),就是有成功安裝 ## Step2 安裝Selenium 在終端機輸入以下指令安裝Selenium ``` pip install selenium ``` ※一定要先裝好Python才能使用pip指令 ## Step3 WebDriver下載 要安裝對應瀏覽器的WebDriver ※(我本來是想用Chrome但不知道為甚麼運行程式時都跟我說版本不符,所以我改用Edge開發) ※如果未來瀏覽器版本更新的話,還是要重新去抓對應版本的WebDriver否則一樣不能用 載點: 1.Chrome:https://sites.google.com/chromium.org/driver/ 2.Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ 3.Firefox:https://github.com/mozilla/geckodriver/releases 4.Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/ 1.載下來之後為左邊的壓縮檔,將它解壓縮就會得到右邊的.exe檔  2.將.exe檔放到與python.exe相同的路徑下【C:\Users\XXX(使用者名稱)\AppData\Local\Programs\Python\Python311(看你裝什麼版本)】  ## Step4 寫程式測試 ※測試:在google搜尋引擎輸入Python並搜尋 1.輸入以下程式碼並運行程式 ``` from selenium.webdriver import Edge from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver = Edge() # 使用Edge的WebDriver driver.get("https://www.google.com/?hl=zh_tw") # 網址導向google搜尋引擎 wait = WebDriverWait(driver, 5) #設置等待時間為5秒 element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "gLFyf"))) element.send_keys("Python")#輸入要搜尋的項目 button = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "gNO89b"))) button.click()#點擊搜尋 while True: pass # 添加無限循環,保持程序運行狀態 ``` 2.如果順利就會跑出以下畫面  ## 參考資料 1.https://medium.com/marketingdatascience/selenium教學-一-如何使用webdriver-send-keys-988816ce9bed 2.https://northbei.medium.com/在windows上安裝python-selenium-簡易教學-eade1cd2d12d 3.https://ithelp.ithome.com.tw/articles/10261845 4.https://ithelp.ithome.com.tw/questions/10209148
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up