当我执行以下代码时:
driver.findElement(By.className("qview-product-name")).click();
我收到以下错误
Session ID: d5df6f837164b1738991e8dc09027fe0
*** Element info: {Using=class name, value=qview-product-name}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:412)
at org.openqa.selenium.By$ByClassName.findElement(By.java:389)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at Logins.bcLogin(Logins.java:140)
at Exception.main(Exception.java:54)
我正在处理的网页肯定包含以下HTML代码,并且我尝试等待适当的时间来执行。
<dd class="qview-product-name">
<span class="note">1 x </span>
<a href="Link_here"_blank">Title</a>
</dd>
我以为我可以很好地使用各种方法来定位元素,但这让我很困惑。关于如何进行故障排除的任何想法?谢谢!
答案 0 :(得分:1)
您需要注意以下几点:
By.className("qview-product-name")
引用父标签<dd>
,可能不是您想要单击的所需元素。相反,您的用例必须是单击<a href="Link_here"_blank">Title</a>
元素。根据最佳做法,在调用click()
时,您需要诱导为elementToBeClickable()
引入 WebDriverWait ,并且可以使用以下任一{ {3}}:
linkText
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Title"))).click();
cssSelector
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("dd.qview-product-name a[href='Link_here']"))).click();
xpath
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//dd[@class='qview-product-name']//a[@href='Link_here' and text()='Title']"))).click();
确保:
@Test
。