Selenium

Python

Installing

pip install selenium

Webdriver

from selenium import webdriver

Chrome Webdriver

Importing Way 1

 

Downloading ChromeDriver

Chrome for Developers: ChromeDriver
下載相應 OS 及 Chorme 版本的 ChromeDriver
放置於 {project} 中

 

Importing

  driver = webdriver.Chrome(“{path_of_project}/[…/][driver/]chromedriver[-headless-shell]-{OS}”)  

Importing Way 2

 

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

service = Service()
options = Options()
options.add_argument("--headless") # headless mode
options.add_argument("--disable-gpu") # disabling GPU
with webdriver.Chrome(service=service, options=options) as driver:
  ...

 

Headless Mode1Chrome for Developers: Chrome Headless Mode

With headless mode, you can run the browser in an unattended environment, without any visible UI.

接管 Chrome

 

遠端偵錯模式啟動 Chrome
  1. cd "C:\Program Files\Google\Chrome\Application\" 
  2. .\chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\Users\<username>\Documents\labs\selenium-profile"

& "C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir="C:\Users\<username>\Documents\labs\selenium-profile"

 

 

連線至前項開啟之 Chrome

 

from webdriver_manager.chrome import ChromeDriverManager

options = Options()
options.debugger_address = "127.0.0.1:9222"

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)

關閉 Webdriver

driver.close()

開啟網頁

driver.get("...")

Finding Web Element(s)2Selenium Dev.: Finding Web Elements

 

...
from selenium.webdriver.common.by import By # since ver. 4.3.0

...
with webdriver.Chrome(service=service, options=options) as driver:
  url = "..."
  driver.get(url)
  element = driver.find_element(By.{locator_strategies}, "...")
  print(element.get_attribute("..."))
  • driver.find_element(By.{locator_strategies}, "...")
  • driver.find_elements(By.{locator_strategies}, "...")

Supported Locator Strategies (since Selenium v4.3.0)

參考:Selenium Dev.: selenium.webdriver.common.by

Get the Attribute of the Active Element

element.get_attribute("...")

Get the Text

element.get_attribute("innerHTML")

NoSuchElementException

from selenium.common.exceptions import NoSuchElementException

Confirming whether the element exists or not3Selenium Dev: Waiting Strategies

Using find_elements()

len(driver.find_elements(By.{locator_strategies}, "...")) == 0

Waiting for the element

 

import time
from datetime import datetime
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

processing_time_limit = ... # minutes
def get_element(xpath):
  nonlocal driver
  start_time = datetime.now()
  while len(driver.find_elements(By.XPATH, xpath)) == 0:
    time.sleep(0.1)
    if (datetime.now() - start_time).total_seconds() > 60 * processing_time_limit:
      raise NoSuchElementException
  return driver.find_element(By.XPATH, xpath)

Using WebDriverWait and expected_conditions

 

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, timeout=10) # [timeout] = seconds

wait.until(
  EC.presence_of_element_located(
    (By.{locator_strategies}, "...")
  )
)

列出子節點

下一層子節點

for child in get_element("...").find_elements(By.XPATH, './*'):
  print(child.tag_name)

所有子節點

for child in get_element("...").find_elements(By.XPATH, './/*'):
  print(child.tag_name)

彈出視窗

彈出視窗分為:

  • alert: 只有確認鍵 (OK)
  • confirm: 有確認鍵 (OK) 和 取消鍵 (Cancel)
  • prompt: 有確認鍵 (OK) 和 取消鍵 (Cancel),還能輸入文字

切換到 alert

alert = driver.switch_to.alert

確認

alert.accept()

取消

alert.dismiss()

輸入文字

alert.send_keys("...")

讀取彈出視窗的提示文字

alert.text

其他各種操作

填寫:input_element.send_keys(“…”)

點擊:element.click()

螢幕截圖

  • driver.get_screenshot_as_png()
    回傳 PNG 格式的 raw data
  • driver.get_screenshot_as_file({file path})
    將螢幕截圖保存至 {file_path}
  • driver.get_screenshot_as_base64()
取得某個 element 的截圖

element.screenshot_as_png

在 Jupyter 中顯示截圖
from IPython.display import Image, display

display(Image(driver.get_screenshot_as_png()))

Last Updated on 2025/05/07 by A1go

References

目錄
Bitnami