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.

開啟網頁

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 not

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

 

Waiting for the element

 

processing_time_limit = ... # seconds
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)

 

各種操作

填寫 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() 

 

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

display(Image(driver.get_screenshot_as_png()))

關閉網頁

driver.close()

Last Updated on 2025/04/11 by A1go

References

目錄
Bitnami