我试图在下面的下拉搜索栏中输入伦敦,但它没有sendKeys。纠结于如何正确抓取元素?我至少可以让搜索加载。
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "/Users/Desktop/chromedriver" );
WebDriver driver = new ChromeDriver();
driver.get("https://www.dlapiper.com/en/uk/");
WebElement peopleButton = driver.findElement(By.id("ui-id-1"));
peopleButton.click();
WebElement peopleAutoComplete = driver.findElement(By.id("peopleglobalsearchbox"));
peopleAutoComplete.sendKeys("London");
这会失败有两个原因。第一,你找错了元素。第二,你会在它在页面上可见之前识别它。
当使用Selenium sendKeys时,你应该引用一个输入字段,而不是div。在这种情况下。
By.xpath("//div[@id='peopleglobalsearchbox']//input");
元素的可见性比较复杂,但Selenium已经很好地支持了这些挑战。
public WebElement waitUntilElementIsVisible(By by) {
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(by));
return driver.findElement(by);
}
上述方法会等到定位器可见,然后再发送键。