如何从 javascript 警报中捕获文本并使用 chrome 无头设置 OK?

How can I catch the text from a javascript alert and set a OK using chrome headless?

伙计们!

如何从 javascript 警报中捕获文本并使用 chrome 无头设置 OK? 以下代码运行良好,但如果我设置无头选项,它似乎找不到弹出警报。

Edit 我意识到我的代码停止在“self.action.move_to_element(firstLevelMenu).perform()”,而不是我想的 javascript 警报。我该如何解决?

import os
from selenium import webdriver from webdriver_manager.chrome import
 ChromeDriverManager from webdriver_manager.firefox import
 GeckoDriverManager from selenium.webdriver.common.keys import Keys
 import time as pausa  from selenium.webdriver.common.by import By from
 selenium.webdriver.common.action_chains import ActionChains from
 selenium.webdriver.support.ui import WebDriverWait from
 selenium.webdriver.support import expected_conditions as EC #olhar
 from selenium.webdriver.remote.webelement import WebElement from
 datetime import datetime from tkinter import * from tkinter import
 scrolledtext,  messagebox, ttk import pyautogui as p import csv import
 datetime from datetime import date, datetime import pyodbc
class Driver:
  def __init__ (self):
    if nav_cbx.get()=='Chrome':
        options = webdriver.ChromeOptions()
        options.add_experimental_option('useAutomationExtension', False)
        # options.add_argument("--headless")
        options.add_argument("--dns-prefetch-disable")
        options.add_argument("--disable-infobars")

        

self.driver = webdriver.Chrome('c:/driver/chromedriver.exe', options=options) #PASTA DO SCRIPT

    self.action = ActionChains(self.driver)
    self.wait = WebDriverWait(self.driver, 30)
    self.wait2 = WebDriverWait(self.driver, 10)
    agora = str(datetime.today()).replace(':', '.')
    
    cria_pasta_log()
    self.log = open(f'{caminho_log()}/log{agora}.csv', "w", newline='\n', encoding='ANSI')

    self.log.write(f'ID;Chpras;Bin;Final;Portador;Status')

    self.login = in_login.get()
    self.senha = in_senha.get()
           


def menu_reemitir(self, chpras):
    self.retorna_frame()
    
    firstLevelMenu = self.driver.find_element(By.XPATH, '//*[@id="imgMenu"]')
    self.action.move_to_element(firstLevelMenu).perform() #menu opções
    secondLevelMenu = self.driver.find_element(By.XPATH, '//*[@id="elem9"]')
    secondLevelMenu.click() #submenu reemitir cartão
    self.driver.switch_to.window(self.driver.window_handles[2]) #alternar para popup
    self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="FormSAT"]/div[2]/table[2]/tbody/tr/td[1]/input'))).click()
    # self.driver.execute_script("modificarReemision()") 
    pausa.sleep(0.5)

    #### THE PROBLEM STARTS RIGHT HERE!!!!!!!!!!!!!!!!!!!!!!!!
    #there's 2 alerts. On the first one I need set an accept

    alert1 = self.wait.until(EC.alert_is_present())
    
    alert1.accept()
    
    
    pausa.sleep(0.5)
    try:
        # on the second one I need cacth the text and set another "ok"
        alert2 = self.wait.until(EC.alert_is_present())
        
        text = alert2.text
        
        alert2.accept()        
        
        print(text)
        
        
        if 'BLOQU' in str(text).upper():
            text = self.captura_msg_bloqueio(chpras)
        
        self.log.write(f'{text};')
        
            
    except:
        self.log.write(f'Não foi possível capturar a mensagem de retorno;')
        self.driver.close()
            
    self.aceita_alerta()
    self.driver.switch_to.window(self.driver.window_handles[1])

    pausa.sleep(0.5)

我真的需要使用 headless 选项,我需要 load/accept 这两个弹出警报。我该怎么做?

您可以覆盖警报以捕获消息:

driver.executeScript("""
  window.alert = message => window.alertMessage = message
""")

以后再拿

message = driver.executeScript("return window.alertMessage")