首页 > 解决方案 > Selenium 通过 css 而不是 id 搜索元素

问题描述

今天我将我的 chrome 驱动程序更新为

If you are using Chrome version 77, please download ChromeDriver 77.0.3865.40

我尝试使用以下代码通过 id 查找元素:

public static void inputValueById(String input,String id)
    {
        WebDriver driver2 = WebDriverMgr.getDriver();
        WebElement element = driver2.findElement(By.id("//input[@id='company']"));
        element.click();
        element.clear();
        element.sendKeys(input);
    }

我得到了这个例外

ERROR: no such element: Unable to locate element: {"method":"css selector","selector":"#\/\/input\[\@id\=\'company\'\]"}
  (Session info: chrome=77.0.3865.90)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'C', ip: '10.9.26.18', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_65'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 77.0.3865.90, chrome: {chromedriverVersion: 77.0.3865.40 

有人可以告诉为什么它是通过 CSS 选择器而不是 ID 搜索的吗?方法":"css 选择器"

标签: seleniumselenium-chromedriver

解决方案


我认为当您尝试通过其 ID 查找元素时,您必须编写如下代码:

driver.findElement(By.id("ID"))

但是你写的是 xpath 而不是 ID。如果你想用这个找到xpath你必须这样写:

 driver.findElements(By.xpath("//input[@id='company']"));

推荐阅读