基于Java的Selenium谷歌页面Alert弹窗处理问题求助
Google页面弹出的不是传统JavaScript Alert,而是Cookie授权模态框,不能用Alert接口处理,需要通过元素定位操作按钮。以下是修改后的代码,核心是加入显式等待定位弹窗按钮并完成操作:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; public class GoogleSearchSteps { WebDriver driver = null; WebDriverWait wait; // 显式等待实例 @Given("browser is open") public void browser_is_open() { String projectPath = System.getProperty("user.dir"); System.out.println("Project Path is "+projectPath); System.setProperty("webdriver.chrome.driver", projectPath+ "/src/test/resources/drivers/chromedriver"); driver = new ChromeDriver(); // 初始化显式等待,替代部分隐式等待的场景 wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); driver.manage().window().maximize(); } @And("user is on the google search page") public void user_is_on_the_google_search_page() { driver.navigate().to("https://www.google.com/"); // 处理Cookie授权弹窗 try { // 针对英文页面的"接受所有Cookie"按钮,若为中文页面可替换为"接受全部" wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Accept all']"))).click(); // 若需要拒绝Cookie,替换为下面的定位(英文页面) // wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Reject all']"))).click(); } catch (Exception e) { // 若弹窗未出现,捕获异常不中断流程 System.out.println("Cookie弹窗未加载或已自动关闭"); } } @When("user enters text in google search bar") public void user_enters_text_in_google_search_bar() { // 用显式等待定位搜索框,提升稳定性 wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("q"))).sendKeys("arsenal"); } @And("hit enter") public void hit_enter() { wait.until(ExpectedConditions.elementToBeClickable(By.name("q"))).sendKeys(Keys.ENTER); } @Then("user is navigated to the search results page") public void user_is_navigated_to_the_search_results_page() { wait.until(ExpectedConditions.textToBePresentInElementLocated(By.tagName("body"), "Arsenal")); driver.quit(); } }
关键说明
- 用
WebDriverWait显式等待替代直接定位,避免页面加载延迟导致的元素找不到问题 - Cookie弹窗的按钮选择器需根据页面语言调整:
- 英文页面接受按钮:
//button[@aria-label='Accept all'] - 中文页面接受按钮:
//button[@aria-label='接受全部'] - 拒绝按钮同理,替换
aria-label属性值即可
- 英文页面接受按钮:
- 加入异常捕获,防止弹窗未出现时脚本中断
内容的提问来源于stack exchange,提问作者Femi Togun
相关产品推荐
相关产品推荐

