为什么我不能用selenium关闭弹出窗口或对话框?

时间:2016-09-06 06:31:50

标签: java selenium

摘要:在下面的网址中,请点击回复按钮。然后,将出现一个弹出窗口并隐藏回复按钮。当您单击空白区域或包含“post id:”的段落时,弹出窗口消失,您可以再次看到回复按钮。我想使用下面的代码来做这些事情。

问题: main中最后3个方法调用都没有弹出窗口消失。我的代码出了什么问题,如何让它运行?

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class Temp {
    private static final WebDriver browser = new ChromeDriver();

    private static String reply_btn_xpath = "//button[contains(concat(\" \", normalize-space(@class), \" \"), \" "
            + "reply_button" + " \")]";
    private static By reply_btn_loc = By.xpath(reply_btn_xpath);

    private static String url = "https://sfbay.craigslist.org/pen/apa/5764613878.html";

    public static void main(String[] args) {
        browser.get(url);
        WebElement reply = browser.findElement(reply_btn_loc);
        reply.click();
        WebElement post_id = browser.findElement(By.xpath("//p[contains(., 'post id:')]"));
        post_id.click();
        click_with_actions(post_id);
        click_with_js(post_id);
    }

    public static void click_with_actions(WebElement element) {
        Actions actions = new Actions(browser);
        actions.moveToElement(element).click().perform();
    }

    public static void click_with_js(WebElement element) {
        ((JavascriptExecutor) browser).executeScript("arguments[0].click();", element);
    }

}

显然,建议不要在VM或CI中使用java.awt.Robot来执行点击,因为它们没有真正的键盘。 Java awt.Robot not working inside a virtual machine?

我也在上面的代码中尝试过Robot,它没有用。

public static void click_with_robot(WebElement element, int x, int y) {
    Robot bot = null;
    try {
        bot = new Robot();
    } catch (AWTException e) {
        e.printStackTrace();
    }
    Point location = element.getLocation();

    int x_loc = location.getX() + x;
    int y_loc = location.getY() + y;

    bot.mouseMove(x_loc, y_loc);

    bot.mousePress(InputEvent.BUTTON1_MASK);
    bot.mouseRelease(InputEvent.BUTTON1_MASK);
}

0 个答案:

没有答案