为什么 Selenium 在 Google 主页上识别一个按钮而不是两个按钮

Why does Selenium identifies one button instead of two buttons on Google Home Page

程序 Objective : - 程序是使用 tagName anchor

搜索出现在 Google 搜索页面上的按钮数量

问题:- 此程序返回结果 1 而不是 2,因为 google 搜索页面

上有两个按钮可用

测试数据:-

  1. JAVA :- java version "1.8.0_121" Java(TM) SE 运行-time Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64 位服务器 VM(内部版本 25.121-b13,混合模式)
    2 个 Selenium 可执行 JAR 文件:-selenium-server-standalone-3.3.1
  2. FF 浏览器:- 52.0.1(64 位)
  3. Eclipse :- Eclipse IDE for Java 开发者版本:Neon.2 Release (4.6.2) Build id:20161208-0600
  4. 壁虎驱动程序:-geckodriver-v0.15.0-win64
  5. 代码试验:

    package com.packt.webdriver.chapter1;
    
    import java.util.List;
    import org.openqa.selenium.*;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class GoogleSearchPageByTagName
    {
        public static void main(String[] args)
        {
            WebDriver driver;
            System.setProperty("webdriver.gecko.driver","C:\Users\PragatiChaturvedi\Desktop\Selenium Web Driver\geckodriver.exe");
            driver =new FirefoxDriver();
            driver.get("http://www.google.com");
            List<WebElement> buttons =driver.findElements(By.tagName("button"));
            System.out.println(buttons.size());
        }
    }
    

控制台输出 :-

1490117595600   geckodriver INFO    Listening on 127.0.0.1:38505
1490117596915   mozprofile::profile INFO    Using profile path C:\Users\PRAGAT~1\AppData\Local\Temp\rust_mozprofile.UbkCPgo5hof6
1490117596926   geckodriver::marionette INFO    Starting browser C:\Program Files (x86)\Mozilla Firefox\firefox.exe with args []
1490117596999   geckodriver::marionette INFO    Connecting to Marionette on localhost:51031
Mar 21, 2017 1:33:55 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1

您正在查找标签名称为 "button" 的元素。

您正在查看的页面中只有其中一个。 (甚至没有显示)

您想要查找属性类型为 "submit" 的标签输入。

尝试

driver.find_element_by_xpath("//input[@type='submit']");

这个问题很棘手。不用说,当我们访问 Google 的 URL 时,我们将被重定向到我们各自的 Google 镜像站点。例如 google.com、Google.co.in,现在启用了本地化 Google 网络服务,这些镜像站点中的按钮数量可能会有所不同。

让我非常困惑的按钮数量的事实是因为按钮被隐藏了。我们通常将它们称为隐藏元素。其中一些按钮仅在典型情况下才会激活,而大多数按钮对最终用户来说根本不可见,但它们仍然存在。虽然隐藏这些按钮的原因将是一个单独的讨论线程,但它们对于实现不同的业务逻辑是必要的。

现在更有趣的是,按钮不一定以按钮标签开头。所以就像这种情况一样,如果你想通过标签 "tagName" 计算按钮的数量,你很可能会得到不正确的结果。有些按钮可能会在输入标签或其他标签中定义。因此,要查找特定网页上的按钮数量,必须按照网页上所有按钮的模式构建 xpath。

现在进入问题。从这个问题来看,OP 实际想要断言的内容并不清楚。但是可见按钮的数量肯定会与开发环境中定义的按钮数量不同。