我有 40 個 Python 單元測驗,每個測驗都打開一個 Selenium 驅動程式,因為它們是單獨的檔案并且不能共享同一個驅動程式。
from selenium import webdriver
webdriver.Firefox()
上述命令會將焦點轉移到新打開的視窗。例如,如果我在我的編輯器上輸入一些東西,在我作業的程序中,突然一個 selenium 瀏覽器正在打開并且 Linux 切換到那個視窗。我不確定 Windows 或 Mac 是否有類似的問題。
這意味著每次我運行一個單元時,我都無法使用我的計算機,因為它一直在切換我當前使用的應用程式。
如何告訴 Selenium 不要切換到打開的視窗?
uj5u.com熱心網友回復:
這是在無頭模式下在 linux 上運行 Selenium/Firefox 的示例。您還可以看到各種進口商品 - 將它們留在那里。瀏覽器將以無頭模式啟動,將轉到 ddg 頁面并列印出頁面源,然后退出。
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options as Firefox_Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
firefox_options = Firefox_Options()
firefox_options.add_argument("--width=1280")
firefox_options.add_argument("--height=720")
firefox_options.headless = True
driverService = Service('chromedriver/geckodriver') ## path where geckodriver is
browser = webdriver.Firefox(service=driverService, options=firefox_options)
wait = WebDriverWait(browser, 20)
browser.get('https://duckduckgo.com')
print(browser.page_source)
browser.quit()
如果任何單元測驗需要,瀏覽器也可以在無頭模式下截屏。
可以在https://www.selenium.dev/documentation/找到結構合理的 Selenium 檔案(當然,有一些差距,但總體上還不錯)。
uj5u.com熱心網友回復:
您可以在無頭模式下運行 Selenium 驅動程式。這將防止將焦點移至由 Selenium 瀏覽器打開,并且不會打擾您在 PC 機器上作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/514455.html
上一篇:my_ip/phpmyadmin在Nginx上顯示404NotFound并且在一個教程之后加載我的網站,它會下載一個檔案
