Try   HackMD

Selenium4.0使用入門 pyhton

slide: https://hackmd.io/@xx78826/get-started-python-selenium4


本文將提供簡單的入門selenium


Who am I?

  • 一位會寫簡單爬蟲的肥宅

入門要知道哪些?


怎麼樣安裝?

pip install selenium

如何查詢現在版本

python
import selenium
selenium.__version__

使用selenium開啟Chrome要準備什麼

檢查自己的Chrome目前是哪個版本號?

到以下網站下載開啟Chrome的版本
https://chromedriver.chromium.org/downloads

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

1.點擊右上角三個點
2.點擊說明
3.點擊 關於 Google Chrome
4.看版本號 版本 104.0.5112.102 (正式版本) (64 位元)

到以下網站下載開啟Chrome的版本
https://chromedriver.chromium.org/downloads

下載If you are using Chrome version 104, please download ChromeDriver 104.0.5112.79

from selenium import webdriver
#引用selenium

driver = webdriver.Chrome("D:\\python-training-2022\\chromedriver.exe")
#需要把剛剛下載的chromedriver.exe路徑放入
#自己是把這個chromedriver.exe放到這個資料夾內D:\python-training-2022

driver.get("這裡面寫網址")
#恭喜可以使用Selenium打開網址了

Selenium4.0版本差別在哪裡

差別1

from selenium.webdriver.common.by import By
#需要在程式碼中import By

差別2

find_element_by_id("")
#以上為3.多版本時用法


find_element(By.ID, "id")
find_element(By.NAME, "name")
find_element(By.XPATH, "xpath")
find_element(By.LINK_TEXT, "link text")
find_element(By.PARTIAL_LINK_TEXT, "partial link text")
find_element(By.TAG_NAME, "tag name")
find_element(By.CLASS_NAME, "class name")
find_element(By.CSS_SELECTOR, "css selector")
#以上為4.0用法 現在用法

Selenium 設定瀏覽器大小 現在大小

最後我們到底視窗是多大?
如果有訊息視窗會error必須要關閉

print(driver.get_window_size().get("width"))
#目前瀏覽器寬大小
print(driver.get_window_size().get("height"))
#目前瀏覽器高大小
driver.set_window_size(1051,806)
#把瀏覽器設定為 寬1051 高806

參考資料來源
開視窗的大小
https://ithelp.ithome.com.tw/articles/10230717
設定視窗的大小
https://stackoverflow.com/questions/23381324/how-can-i-control-chromedriver-open-window-size