javascript 如何使用 Selenium 单击网页上的打印按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26522739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:04:50  来源:igfitidea点击:

How to click on the print button on a web page using Selenium

javajavascriptgoogle-mapsseleniumnavigation

提问by FaNaJ

I want to click on the print button in this page :

我想单击此页面中的打印按钮:

https://www.google.com/maps/dir/40.4515849,-3.6903752/41.380896,2.1228198/@40.4515849,-3.6903752/am=t/?hl=en

https://www.google.com/maps/dir/40.4515849,-3.6903752/41.380896,2.1228198/@40.4515849,-3.6903752/am=t/?hl=en

enter image description here

在此处输入图片说明

and then save the PDF...

然后保存PDF...

enter image description here

在此处输入图片说明

this is the code for click the button:

这是单击按钮的代码:

String url = "https://www.google.com/maps/dir/40.4515849,-3.6903752/41.380896,2.1228198/@40.4515849,-3.6903752/am=t/?hl=en";

WebDriver driver = new HtmlUnitDriver();
driver.get(url);

System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());

WebElement element = driver.findElement(By.xpath("//*[@id=\"text-mode-options-header\"]/div/div/div[2]/div[2]/div/button[1]"));
element.click();

System.out.println("Page title is: " + driver.getTitle());
driver.quit();

but I get the following error:

但我收到以下错误:

    Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate a node using //*[@id="text-mode-options-header"]/div/div/div[2]/div[2]/div/button[1]
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.43.1', revision: '5163bce', time: '2014-09-10 16:27:58'
Driver info: driver.version: HtmlUnitDriver
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByXPath(HtmlUnitDriver.java:1057)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:357)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.call(HtmlUnitDriver.java:1575)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.call(HtmlUnitDriver.java:1)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:1251)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1572)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:532)
    at com.controlstation.start.Main.main(Main.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

how can I do this using Selenium? is there another way? thanks.

我如何使用 Selenium 做到这一点?还有另一种方法吗?谢谢。

EDIT:

编辑:

enter image description here

在此处输入图片说明

回答by alecxe

Here's my insight.

这是我的见解。

First of all, you need to wait for the page to load in order to interact with the Printbutton. The best way to go is to use built-in mechanism: selenium waits- wait for the Printbutton to be clickable:

首先,您需要等待页面加载才能与Print按钮进行交互。最好的方法是使用内置机制:硒等待- 等待Print按钮可点击

// open print dropdown
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.print-button"))).click();

// click print button
WebElement printButton = driver.findElement(By.cssSelector("button.print-popup-button"));
printButton.click();


Okay, if you run it using ChromeDriver:

好的,如果您使用ChromeDriver以下命令运行它:

package com.company;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


public class Main {
    public static void main(String[] args) {
        String url = "https://www.google.com/maps/dir/40.4515849,-3.6903752/41.380896,2.1228198/@40.4515849,-3.6903752/am=t/?hl=en";

        WebDriver driver = new ChromeDriver();
        driver.get(url);

        // open print dropdown
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.print-button"))).click();

        // click print button
        WebElement printButton = driver.findElement(By.cssSelector("button.print-popup-button"));
        printButton.click();

        // now what? 
    }
}

You'll see the Chrome Print Previewdialog, which is, unfortunately, out of scope for selenium:

您将看到Chrome 打印预览对话框,不幸的是,这超出了 selenium 的范围:

enter image description here

在此处输入图片说明

But, there is a hope, if you examine available Chrome arguments, you would see that there is the relevant one:

但是,有一种希望,如果您检查可用的Chrome 参数,您会发现有相关的参数:

--disable-print-preview - Disables print preview (For testing, and for users who don't like us. :[ )

--disable-print-preview - 禁用打印预览(用于测试和不喜欢我们的用户。:[ )

Okay, let's try it out:

好的,让我们试一试:

ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-print-preview");

WebDriver driver = new ChromeDriver(options);
driver.get(url);

Now, there is a system print dialog being shown:

现在,显示了一个系统打印对话框:

enter image description here

在此处输入图片说明

Selenium cannot control it too. So, nope, there is no hope. Oh, wait!

Selenium 也无法控制它。所以,不,没有希望。等一下!



Okay, if we are out of scope of selenium, let's use tools that can help us to click that Printbutton in the dialog - Robotclass:

好的,如果我们超出了 selenium 的范围,让我们使用可以帮助我们Print在对话框中单击该按钮的工具-Robot类:

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed.

此类用于生成本地系统输入事件,以用于测试自动化、自运行演示以及需要控制鼠标和键盘的其他应用程序。

We'll initialize the Robotand will send Enterkey when the print dialog would show up:

当打印对话框出现时,我们将初始化Robot并发送Enter密钥:

package com.company;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.awt.*;
import java.awt.event.KeyEvent;


public class Main {
    public static void main(String[] args) throws AWTException, InterruptedException {
        String url = "https://www.google.com/maps/dir/40.4515849,-3.6903752/41.380896,2.1228198/@40.4515849,-3.6903752/am=t/?hl=en";

        Robot r = new Robot();
        r.delay(1000);

        WebDriver driver = new ChromeDriver();
        driver.get(url);

        // open print dropdown
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.print-button"))).click();

        // click print button
        WebElement printButton = driver.findElement(By.cssSelector("button.print-popup-button"));
        printButton.click();

        Thread.sleep(2000);

        r.keyPress(KeyEvent.VK_ENTER);
        r.keyRelease(KeyEvent.VK_ENTER);
    }
}

Other options are to use:

其他选项是使用:

  • sikuli- you would need an image of the print button in order for sikuli to locate it and click
  • autoit
  • sikuli- 您需要打印按钮的图像,以便 sikuli 找到它并单击
  • autoit

Also see:

另见:

回答by JoriO

This way you can click the Print including maps-option (sorry, but it is in C#):

这样你就可以点击 - 选项Print including maps(抱歉,它是在 C# 中):

Actions builder = new Actions(Driver);
builder.MoveToElement(Driver.FindElement(By.ClassName("print-button"))).Click()
       .MoveToElement(Driver.FindElements(By.ClassName("print-popup-button"))[0]).Click().Build().Perform();            

But! In your question you had a picture of Chrome print preview window, which I think won't be available with HtmlUnitDriver, which your code is using. You can always run the test with chromedriver, but it seems like the print preview is out of scope for selenium, ie. you can't control it with webdriver. To my knowledge the same is true for system print dialog, which appears with firefox. If HtmlUnitDriver behaves differently in this case, then you'll be fine, but I'm afraid you are going to face a problem here.

但!在您的问题中,您有一张 Chrome 打印预览窗口的图片,我认为该图片不适用于您的代码正在使用的 HtmlUnitDriver。您始终可以使用 chromedriver 运行测试,但似乎打印预览超出了 selenium 的范围,即。你不能用 webdriver 控制它。据我所知,系统打印对话框也是如此,它出现在 Firefox 中。如果 HtmlUnitDriver 在这种情况下表现不同,那么你会没事的,但恐怕你会在这里遇到问题。

回答by Bob Ezuba

Just to add to what @JoriO posted, Can you please test to see if the web element exists before clicking on it using Selenium? If it doesn't exists, add a thread sleep statement after driver.get(url)... Reason being that Selenium may try to click before the driver finishes loading the page. This has fixed most of the problems I have experienced using Selenium error "No Such Element Exception"

只是为了添加@JoriO 发布的内容,您能否在使用 Selenium 单击 Web 元素之前先测试一下它是否存在?如果它不存在,请在 driver.get(url) 之后添加一个线程 sleep 语句...原因是 Selenium 可能会在驱动程序完成加载页面之前尝试点击。这解决了我在使用 Selenium 时遇到的大部分问题,错误“没有这样的元素异常”