--- disqus: ahb0222 GA : G-CQ4L16KHK4 --- # Python Selenium使用紀錄 > [color=#40f1ef][name=LHB阿好伯, 2021/07/16][:earth_africa:](https://www.facebook.com/LHB0222/) ###### tags: `Python_30` `Python` `爬蟲` [TOC] # 安裝 ## 安裝selenium :::success pip install selenium ::: ![](https://i.imgur.com/sEuNXlp.png) ## 安裝瀏覽器驅動 在瀏覽器設定->關於中找到瀏覽器版本 ![](https://i.imgur.com/54MbCVP.png) |瀏覽器|驅動| | -------- | -------- | | Chrome: | <https://chromedriver.chromium.org/downloads> | | Edge: | <https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/> | | Firefox: | <https://github.com/mozilla/geckodriver/releases> | | Safari: | <https://webkit.org/blog/6900/webdriver-support-in-safari-10/> | 下載合適的驅動 ![](https://i.imgur.com/CSiQEYM.png) 啟動驅動 ![](https://i.imgur.com/va5PiP1.png) # 常用函數 ## 開啟、關閉瀏覽器 ```python= # 載入需要的套件 from selenium import webdriver from selenium.webdriver.common.keys import Keys # 開啟瀏覽器視窗(Chrome) driver = webdriver.Chrome() ``` ![](https://i.imgur.com/T19FTCd.png) ```python=+ # 關閉瀏覽器 driver.quit() #直接退出 driver.close() #關閉當前分頁 ``` ## 開啟特定網頁 ```python= driver.get("https://wq.epa.gov.tw/EWQP/zh/EnvWaterMonitoring/RiverWaterQuality.aspx") ``` ![](https://i.imgur.com/gbaT9Dd.png) ## 定位 定位到網頁上某個物件需要使用函數find_element_by_* 總共有8種定位方式可以選擇 :::success find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector ::: ### 滑鼠點擊 這時再搭配 `.click()` 就可以模擬滑鼠點擊的動作去選擇清單中的選項 ```python= 點擊水質查詢 elem = driver.find_element_by_xpath('//li[(((count(preceding-sibling::*) + 1) = 1) and parent::*)]//*[contains(concat( " ", @class, " " ), concat( " ", "Advanced", " " ))]') elem.click() ``` import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') # 取得文字 elem.text # 故障排除 ## Chrome版本太新 下載舊版本 https://github.com/vikyd/note/blob/master/chrome_offline_download.md 若是會自動更新 在搜尋欄上輸入**services.msc**,找到程式後點選執行 ![image](https://hackmd.io/_uploads/B11JjGtFp.png) ![image](https://hackmd.io/_uploads/B1smjMtK6.png) 停用更新 ![image](https://hackmd.io/_uploads/S1kDoMYKp.png) # 爬取codis氣候資料服務系統 [爬取codis氣候資料服務系統](/LW3Ys5qwQ4a4j6zrOdc8HA) ![ggplot2](https://hackmd.io/_uploads/HkEbvQFYp.gif) >參考 >https://selenium-python-zh.readthedocs.io/en/latest/ 🌟參考資料 https://selenium-python-zh.readthedocs.io/ 🌟全文可以至下方連結觀看或是補充 全文分享至 https://www.facebook.com/LHB0222/ https://www.instagram.com/ahb0222/ 有疑問想討論的都歡迎於下方留言 喜歡的幫我分享給所有的朋友 \o/ 有所錯誤歡迎指教 # [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings) ![](https://i.imgur.com/nHEcVmm.jpg)