【发布时间】:2021-09-14 14:59:13
【问题描述】:
我正在尝试使用 Selenium + Java 单击网站上的一个按钮,但是单击这个特定按钮没有运气(我可以单击并输入其他字段,但这个特别给我带来了麻烦)。
这是 HTML 的样子,这是我需要单击的图像:
<div class="sc-dIUggk XavQL">
<a href="www.someWebsite.com" target="_top" name="tempo-reports-menu-item" class="sc-fbNXWD eXJbNH">
<div class="sc-GTWni jPMpTI">
<svg width="48" height="48" viewBox="0 0 48 48">
<g transform="translate(13 13)" fill="none" fill-rule="evenodd">
<rect stroke="#004976" stroke-width="1.5" fill-opacity="0.64" fill="#00D8F6" fill-rule="nonzero" x="0.75" y="0.75" width="20.5" height="20.5" rx="2"></rect>
<rect fill="#004976" x="14" y="5" width="2" height="13" rx="0.5"></rect>
<rect fill="#004976" x="10" y="12" width="2" height="6" rx="0.5"></rect>
<rect fill="#004976" x="6" y="9" width="2" height="9" rx="0.5"></rect>
</g>
</svg>
</div>
</a>
</div>
这是我以前尝试点击"//a[@name,'tempo-reports-menu-item']"的xpath,它的用法是这样的driverexec.clickByXpath("Click Reports", "//a[@name,'tempo-reports-menu-item']");
ClickByXpath() 只是我通过 xpath 进行点击的后端代码。
无论我做什么,要么找不到元素,要么无法点击。
EDIT->我也试过这个xpath:
driverexec.clickByXpath("Click Reports", "//*[name()='svg']//*[name()='rect']/ancestor::a[@name='tempo-reports-menu-item']");
如果我在 DOM 中搜索这个 xpath,找到但仍然无法点击。
这是错误信息:
Expected condition failed: waiting for element to be clickable: By.xpath: //*[name()='svg']//*[name()='rect']/ancestor::a[@name='tempo-reports-menu-item']
这是我的函数'clickByXpath()`:
public boolean clickByXpath(String description, String xpath) throws Exception {
int retry = 0;
while (retry <= maxAttempts) {
try {
delayFor(2500);
driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
driver.findElement(By.xpath(xpath)).click();
delayFor(500);
// System.out.println("clicked " + description);
System.out.println("clicked " + description);
return true;
} catch (Exception e) {
retry++;
// System.out.println("retrying click by xpath for row " + row + " with xpath " + xpath);
if (retry > maxAttempts) {
System.out.println("now not retrying");
String message = "Could not click [" + description + "] with xpath " + xpath;
System.out.println("failed to click with error: " + e.getMessage());
failure(message);
return false;
}
}
}
return false;
}
【问题讨论】:
-
UI 的屏幕截图很棒,代码或 HTML 的屏幕截图则不然。请阅读为什么a screenshot of code/HTML is a bad idea。粘贴代码/HTML 并正确格式化。
-
您还需要在您的问题中以正确格式的文本形式发布完整的错误消息。我们无法评估我们看不到的代码...您需要为
.clickByXpath()添加代码。您是否使用$x()在浏览器中测试过您的定位器? -
好的,我添加了属于我要单击的项目的 HTML。我不确定您所说的
$x()是什么意思?我可以在检查 HTML 后控制 + F 并粘贴到我的问题中的 Xpath 中,它在 HTML 中以黄色突出显示,但如果我用 $x() 包围 xpath 则没有任何反应 -
没关系,我明白你的意思,是的,如果我使用 $x(),那么我会在控制台中返回一个元素
-
//a[@name='tempo-reports-menu-item']//*[name()='svg'] 试试这个
标签: java html selenium selenium-webdriver xpath