gpt4 book ai didi

java - Selenium CSS 选择器

转载 作者:行者123 更新时间:2023-12-02 02:28:06 24 4
gpt4 key购买 nike

我是 Selenium 的新手。我正在尝试使用以下代码在 Stack Overflow 网站上运行一个套件。该代码生成 NoSuchElement 异常。我正在使用 selenium java 客户端和服务器(3.7.1)以及 Chrome 驱动程序(2.33)。使用 Java 9。在 Windows 10 上。

我已使用 Chrome 开发者工具上的查找功能验证了 css 选择器。

可能是什么问题?

public class Suite {

private static final String home = "https://stackoverflow.com";
private WebDriver driver = null;

public static void main(String[] args) {

Suite suite = new Suite(true);

suite.login()
.clickByCSSSelector("a.my-profile");

}
public Suite(boolean isHeadLess) {

ChromeOptions option = new ChromeOptions();
if (isHeadLess) option.addArguments("--headless");
System.setProperty("webdriver.chrome.driver", "D:\\work\\webscraping\\chromedriver\\chromedriver.exe");

driver = new ChromeDriver(option);
}
public Suite login() {

this.navigate(home)
.setValue("email", "xxxx@gmail.com")
.setValue("password", "xxxxxx")
.click("submit-button");
return this;

}
public Suite navigate(String target) {
driver.navigate().to(target);
return this;
}
public Suite setValue(String elementId, String value) {
driver.findElement(By.id(elementId)).sendKeys(value);
return this;
}
public Suite clickByXpath(String xpath) {
this.findByXpath(xpath).click();
return this;
}
public Suite clickByCSSSelector(String selector) {
this.findByCSSSelector(selector).click();
return this;
}
private WebElement findByCSSSelector(String selector) {
return driver.findElement(By.cssSelector(selector));

}
public WebElement findByXpath(String xpath) {
return this.find(By.xpath(xpath));
}

public WebElement find(By element) {
return driver.findElement(element);
}
public Suite click(String elementId) {
this.find(elementId).click();
return this;
}
public WebElement find(String elementId) {
return this.find(By.id(elementId));
}

}

异常(exception):

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"a.my-profile"}
(Session info: headless chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:01:39.354Z'
System info: host: 'HMECL000593', ip: '10.0.75.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '9'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptSslCerts: true, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.33.506120 (e3e53437346286..., userDataDir: C:\Users\TOMS~1.VAR\AppData...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 62.0.3202.94, webStorageEnabled: true}
Session ID: fa8665d6bf99e34431e27b91ec3a1458
*** Element info: {Using=css selector, value=a.my-profile}
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:370)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:464)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:430)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:362)
at com.tv.webscraping.selenium.SeleniumClient.findByCSSSelector(SeleniumClient.java:81)
at com.tv.webscraping.selenium.SeleniumClient.clickByCSSSelector(SeleniumClient.java:76)
at com.tv.webscraping.selenium.Suite.main(Suite.java:19)

Chrome 开发者工具:

enter image description here

最佳答案

您可能还需要在点击之前等待

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

在此处查看有关等待的更多信息:WebDriver - wait for element using Java

如果这不起作用,请尝试以下 xpath,并结合上面的等待 .clickByXpath("//a[contains(@class, 'my-profile')]");

下面有更多信息来解释 xpath:

  • 多个匹配://div[@class='class' and contains(text(), 'text')]
  • 部分匹配://span[contains(class, 'class')]
  • starts-with: //input[starts-with(@name,'input')这些在处理动态元素时更有益并且更稳健。

在此处查看有关 xpath 的更多信息:https://sqa.stackexchange.com/questions/10342/how-to-find-element-using-contains-in-xpath

请注意:我仅建议当元素是动态的或没有唯一 ID 时使用 xpath

此外,您可以使用类名而不是 xpath,我在 C# 中执行此操作的示例是 driver.FindElement(By.ClassName("my-profile js-gps-track");

如果上述所有方法都不起作用,您可能需要使用如下操作:

Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id(id)));
actions.click();
actions.build().perform();

关于java - Selenium CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529221/

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