Java 如何单击 Selenium Webdriver 中的链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21759479/
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-08-13 10:31:05  来源:igfitidea点击:

How to Click a Link in Selenium Webdriver

javaselenium-webdriver

提问by Learner

Ima trying to click all the elements present in the Html

我试图点击 Html 中存在的所有元素

http://www.flipkart.com/Under this Electronics -> Shop by Categories ->

http://www.flipkart.com/在此电子产品下 -> 按类别购物 ->

below is the sample part of the Html

下面是 Html 的示例部分

<a class="" data-tracking-id="0_Samsung" href="/mobiles/samsung~brand/pr?sid=tyy,4io&amp;otracker=hp_nmenu_sub_electronics_0_Samsung">Samsung</a>

<a class="" data-tracking-id="0_All Brands" href="/mobiles/pr?sid=tyy,4io&amp;otracker=hp_nmenu_sub_electronics_0_All%20Brands">All Brands</a>


<a class="" data-tracking-id="0_All Brands" href="/laptops/pr?sid=6bo,b5g&amp;otracker=hp_nmenu_sub_electronics_0_All%20Brands">All Brands</a>

iam clicking using below

我点击使用下面

 WebElement ul = driver.findElement(By.id("menu-electronics-tab-0-content"));
       List<WebElement> lis = ul.findElements(By.tagName("li"));
       System.out.println(""+lis.size());
       String[] linksText = new String[lis.size()];
       int index = 0;
       for(WebElement element : lis){

           linksText[index] = element.getText();

        String string = linksText[index];

        if(string.contains(" ")){
            linksText[index]= string.substring(0, string.indexOf(" ")); 
        }

           index++;
       }     
               for(index =0; index < linksText.length; index++){
           String xpath = "//*[contains(@href,'%s')]";
           String y = linksText[index];
                   String xpathOfElement = String.format(xpath, String.valueOf(y));
                      System.out.println("Name 1  "+driver.findElement(By.xpath(xpathOfElement)).getText());
                   driver.manage().timeouts().implicitlyWait(50000, TimeUnit.MILLISECONDS);

                          driver.findElement(By.xpath(xpathOfElement)).click();

When iam running the code it is proceeding till i = 12 till HP after that it is throwing an error. there are 83 Elements present. i need to click and navigate back

当我运行代码时,它会一直运行到 i = 12 直到 HP,然后它才会抛出错误。有 83 个元素存在。我需要点击并导航回来

Name 1  Mobiles
Name 1  Bluetooth Headsets
Name 1  Laptops
Name 1  Apple
Name 1  
FAILED: Electronic
org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Command duration or timeout: 50.20 seconds
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'
System info: host: 'VALUED-8JGOG5PH', ip: '192.168.1.4', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_45'
Session ID: 7d9304d9-fe1a-444d-b6b6-4669bfc46a33
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, browserConnectionEnabled=true, webStorageEnabled=true, nativeEvents=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=26.0}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:79)
    at Examples.FlipkartTest2.Electronic(FlipkartTest2.java:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Element is not currently visible and so may not be interacted with
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'
System info: host: 'VALUED-8JGOG5PH', ip: '192.168.1.4', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_45'
Driver info: driver.version: unknown
    at <anonymous class>.fxdriver.preconditions.visible(file:///C:/Users/ADMINI~1/AppData/Local/Temp/anonymous281959659031274025webdriver-profile/extensions/[email protected]/components/command_processor.js:8179)
    at <anonymous class>.DelayedCommand.prototype.checkPreconditions_(file:///C:/Users/ADMINI~1/AppData/Local/Temp/anonymous281959659031274025webdriver-profile/extensions/[email protected]/components/command_processor.js:10814)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/ADMINI~1/AppData/Local/Temp/anonymous281959659031274025webdriver-profile/extensions/[email protected]/components/command_processor.js:10831)
    at <anonymous class>.fxdriver.Timer.prototype.setTimeout/<.notify(file:///C:/Users/ADMINI~1/AppData/Local/Temp/anonymous281959659031274025webdriver-profile/extensions/[email protected]/components/command_processor.js:396)

is there any alternate method other than href to click the Link.

除了 href 之外,是否还有其他方法可以单击链接。

采纳答案by barak manos

Here is an optional solution for you:

这是您的可选解决方案:

  1. Iterate all the links, and save the values of their <href>attributes in a list.
  2. Iterate the list generated on the previous step, and navigate you browser to each URL.
  1. 迭代所有链接,并将它们的<href>属性值保存在列表中。
  2. 迭代上一步生成的列表,然后将浏览器导航到每个 URL。

Doing it this way will ensure that your code does not depend on the WebElementobjects that you read from the DOM of the original web-page, and once you've collected all the URLs, you no longer need to remain on this web-page.

这样做将确保您的代码不依赖于WebElement您从原始网页的 DOM 中读取的对象,并且一旦您收集了所有 URL,您就不再需要停留在该网页上。

Step #1:

第1步:

Before iterating lis, add ArrayList<String> urls = new ArrayList<String>();

在迭代之前lis,添加ArrayList<String> urls = new ArrayList<String>();

Step #2:

第2步:

Replace driver.findElement(By.xpath(xpathOfElement)).click();

代替 driver.findElement(By.xpath(xpathOfElement)).click();

With urls.add(driver.findElement(By.xpath(xpathOfElement)).getAttribute("href"));

urls.add(driver.findElement(By.xpath(xpathOfElement)).getAttribute("href"));

Step #3:

第 3 步:

After iterating lis, navigate to each URL:

迭代后lis,导航到每个 URL:

for (String url : urls)
    driver.get("http://www.flipkart.com"+url);