什麼是selenium
Selenium 是 ThoughtWorks 提供的一個強大的基於瀏覽器的開源自動化測試工具。
Selenium 是一個用於 Web 應用程序測試的工具,測試直接自動運行在瀏覽器中,就像真正的用戶在手工操作一樣。支持的瀏覽器包括 IE、Chrome 和 Firefox 等。這個工具的主要功能包括:測試與瀏覽器的兼容性 - 測試您的應用程序看是否能夠很好地工作在不同瀏覽器和操作系統之上;測試系統功能 - 創建迴歸測試檢驗軟件功能和用戶需求;支持自動錄製動作,和自動生成 .NET、Perl、Python、Ruby 和 Java 等不同語言的測試腳本。
安裝python
安裝selenium
pip install selenium
檢測selenium
pip show selenium
(venv) ➜ pytest pip show selenium
Name: selenium
Version: 4.1.0
Summary:
Home-page: https://www.selenium.dev
Author:
Author-email:
License: Apache 2.0
Location: /Users/terwer/Documents/PycharmProjects/pytest/venv/lib/python3.8/site-packages
Requires: trio, trio-websocket, urllib3
Required-by:
安裝driver
firefox
下載geckdriver
下載地址:https://github.com/mozilla/geckodriver/releases ,需注意的是瀏覽器的版本和driver驅動的版本要匹配
Google chrome
(Chrome對應Chromedriver,ie對應IEdriver)
下載對應版本的壓縮包,然後解壓,解壓後的名稱都是一樣的,driver的路徑可以放在python的script的路徑下
https://chromedriver.chromium.org/downloads
錯誤解決
'chromedriver' executable needs to be in PATH.
找到文檔
https://chromedriver.chromium.org/getting-started
edge
https://docs.microsoft.com/zh-cn/microsoft-edge/webdriver-chromium/?tabs=python
python運行第一個自動化腳本
from selenium import webdriver
def print_hi(name):
driver = webdriver.Chrome("./chromedriver")
driver.get("https://www.baidu.com")
driver.quit()
print(f'Hi, {name}')
if __name__ == '__main__':
print_hi('Selenium')
解決自動退出
python+selenium自動化,沒有寫close和quit,瀏覽器窗口會自動關閉解決方案
加參數
option.add_experimental_option("detach", True)
完整的代碼
# 加啓動配置
option = webdriver.ChromeOptions()
# 關閉“chrome正受到自動測試軟件的控制”
# V75以及以下版本
# option.add_argument('disable-infobars')
# V76以及以上版本
option.add_experimental_option('useAutomationExtension', False)
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# 不自動關閉瀏覽器
option.add_experimental_option("detach", True)
driver = webdriver.Chrome("./chromedriver", chrome_options=option)
driver.get("https://www.baidu.com")
driver.maximize_window()
# driver.quit()
edge版本
from msedge.selenium_tools import Edge, EdgeOptions
import os
def start_dege():
options = EdgeOptions()
options.binary_location = r'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'
options.use_chromium = True
options.set_capability("platform", "Mac OS")
# 不退出
options.add_experimental_option("detach", True)
browser = Edge(options=options, executable_path=r"/usr/local/bin/msedgedriver")
browser.get('http://localhost:8090')
def close_edge():
os.system("killall -9 'Microsoft Edge'")
print("previous Microsoft Edge is closed")
if __name__ == '__main__':
close_edge()
start_dege()
print("edge started")
全屏
option.add_argument("--start-maximized")
option.add_argument('window-size=2560,1440')