gpt4 book ai didi

java - 由于 XPath 表达式不正确,Selenium "Element not found"

转载 作者:行者123 更新时间:2023-12-01 12:16:40 25 4
gpt4 key购买 nike

我对 Selenium 和 XPath 完全陌生。今天是我第一次尝试使用 Selenium RC 执行一个简单的脚本。 。请找到下面的代码。

package com.rcdemo;

import org.junit.Test;
import org.openqa.selenium.By;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class MathTest {

@SuppressWarnings("deprecation")
public static void main(String[] args) throws InterruptedException {

// Instatiate the RC Server
Selenium selenium = new DefaultSelenium("localhost", 4444 , "*firefox C:/Program Files (x86)/Mozilla Firefox/firefox.exe", "http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();

// Click on Link Math Calculator
selenium.click("xpath=.//*[@id='menu']/div[3]/a");
Thread.sleep(4500); // Wait for page load

// Click on Link Percent Calculator
selenium.click("xpath=//*[@id='content']/ul/li[3]/a");
Thread.sleep(4000); // Wait for page load


// Focus on text Box
selenium.focus("name=cpar1");
// Enter a value in Text box 1
selenium.type("css=input[name=\"cpar1\"]", "10");

// Enter a value in Text box 2
selenium.focus("name=cpar2");
selenium.type("css=input[name=\"cpar2\"]", "50");

// Click the Calculate button
selenium.click("xpath=.//*[@id='content']/table/tbody/tr/td[2]/input");

// Verify if the result is 5
String result = selenium.getText("//*[@id='content']/p[2]/span/font/b");
System.out.println(result);

if (result == "5") {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}

问题是执行上述代码时,getText() 行发生异常。我从 developer tools 复制了该 XPath谷歌浏览器。即使我手动检查一次,也会显示相同的 XPath 表达式。从今天早上开始我就试图找到这个问题的解决方案。如何让 Selenium 找到该元素?

PS:在结果变量中,我必须捕获计算后的结果。例如,10 % 50 = 5。我需要捕获这 5。

最佳答案

您需要等待“结果”被填充。

这是更新后的代码片段。它应该适合你:

    // Add this line
if (!selenium.isElementPresent("//*[@id='content']/p[2]/span/font/b"))
{
Thread.sleep(2000);
}
// Verify if the result is 5
String result = selenium.getText("//*[@id='content']/p[2]/span/font/b");
System.out.println(result);

// Update this line
if (result.trim().equals("5"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}

并且需要使用.equals方法来比较两个字符串值。

注意 - 更好的方法是用动态等待方法替换 Thread.sleep,例如 waitForPageToLoad、waitForElementPresent(自定义方法)等。

关于java - 由于 XPath 表达式不正确,Selenium "Element not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26957321/

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