gpt4 book ai didi

java - 为什么元素只能通过 javascript 或 selenium 中的操作来点击?

转载 作者:行者123 更新时间:2023-11-30 02:50:16 31 4
gpt4 key购买 nike

在下面的页面中,我想单击住房类型菜单,以便我可以选择公寓等。菜单没有显示,但代码没有失败。它在最后一行失败,但有异常(exception)。

org.openqa.selenium.ElementNotVisibleException: element not visible

当我在 Debug模式下运行代码并手动单击菜单时,它会通过。发生了什么以及为什么?

public void dummy() {
String url = "https://sfbay.craigslist.org/search/pen/apa?hasPic=1&search_distance=25&" +
"postal=94014&nh=75&nh=80&min_price=1500&max_price=2500&bedrooms=1&bathrooms=1";
browser.get(url);
WebElement expand = browser.findElement(By.id("plusminus_housing_type"));
Actions actions = new Actions(browser);
actions.moveToElement(expand).click().perform();//ERROR ! Does not reveal housing types.
WebElement house = browser.findElement(By.id("ul_housing_type"));
WebElement apartment = house.findElement(By.xpath("//li[contains(., 'apartment')]//input"));
apartment.click();
}

当我使用 javascript 而不是操作时,菜单会显示,但我得到一个异常(exception),即“公寓”元素不可单击。要解决这个问题,我必须使用 JavaScript 单击它,如下所示:

((JavascriptExecutor) browser).executeScript("arguments[0].click();", anyElement);

令人惊讶的是,不需要操作或 JavaScript 来显示“邻居”菜单。

我不想只是让代码工作。我需要了解发生了什么。

最佳答案

实际上,带有 id plusminus_housing_typeExpand 按钮隐藏在滚动条内,selenium 会点击元素,就像用户点击页面一样。

假设您是用户,并且您要单击展开按钮,如果不向下滚动,则无法单击此按钮才能到达此按钮。

根据相同的行为,selenium click() 方法有效,而 JavaScript click 仅在内部触发事件,这与用户的观点不正确。

因此,由于这个原因,您无法使用简单的selenium click进行点击,这里您需要实现WebDriverWait并提供适当的等待ExpectedConditions用于在向下滚动后与这些元素进行交互,如下所示:-

browser.get(url);

WebDriverWait wait = new WebDriverWait(browser, 10);

//Now find the expand button first
WebElement expand = wait.until(ExpectedConditions.elementToBeClickable(By.id("plusminus_housing_type")));

//Now scroll down and reach to the button
((JavascriptExecutor) browser).executeScript("arguments[0].scrollIntoView();", expand);
//Now click on expand button
expand.click();

//Now wait until apartment checkbox visible and then find
WebElement apartment = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("apartment_1")));
//Now click on apartment check box
apartment.click();

关于java - 为什么元素只能通过 javascript 或 selenium 中的操作来点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910008/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com