[英]How to convert WebElement to a string for an 'if' statement in selenium/Java
[英]How to use if statement for a WebElement
我正在测试一个股票网站
我在每只股票的页面上都有一个“时钟”,以显示该股票当前是否开/关进行交易
closed : class="inlineblock redClockBigIcon middle isOpenExchBig-1"
opened : class="inlineblock greenClockBigIcon middle isOpenExchBig-1014"
唯一的属性是“类”。 我想使用'if'语句,以便区分它们,我试图在'closed'状态下运行它(请参阅下面“ Check”的代码,从底部开始的12行)。
它在循环的第三次抛出异常:
org.openqa.selenium.NoSuchElementException:没有这样的元素
为什么? 请问如何解决?
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.investing.com");
driver.navigate().refresh();
driver.findElement(By.cssSelector("[href = '/markets/']")).click();;
// list |
int size = 1;
for (int i = 0 ; i < size ; ++i) {
List <WebElement> list2 = driver.findElements(By.cssSelector("[nowrap='nowrap']>a"));
//Enter the stock page
size = list2.size();
Thread.sleep(3000);
list2.get(i).click();
**//Check**
WebElement Status = null;
if (Status == driver.findElement(By.cssSelector("[class='inlineblock redClockBigIcon middle isOpenExchBig-1']")))
{
System.out.println("Closed");
}
// Print instrument name
WebElement instrumentName = driver.findElement(By.cssSelector("[class='float_lang_base_1 relativeAttr']"));
System.out.println(instrumentName.getText());
Thread.sleep(5000);
driver.navigate().back();
}
}
}
尝试使用
WebElement Status = null;
if (Status == driver.findElement(By.className("redClockBigIcon")))
{
System.out.println("Closed");
}
您的循环不会运行3次,但这不是这里的问题。
您正在使用findElement
,它返回一个WebElement或如果找不到该元素则抛出错误。 如果您在页面上并且不知道库存是否开放,则有两种选择:
NoSuchElementExceptions
。 如果抛出此错误,则找不到关闭的类,因此页面打开。 findElements
代替findElement
。 这将返回元素列表,并且如果Selenium找不到任何元素,则不会引发异常。 获取列表后,只需检查列表中的元素数即可。 选项1:
boolean isClosed = false;
try {
isClosed = driver.findElement(By.cssSelector("[class='redClockBigIcon']")).isDisplayed();
}
catch (NoSuchElementException) {
isClosed = false;
}
选项2:
List<WebElement> closedClockElements = driver.findElements(By.cssSelector("[class='redClockBigIcon']"));
if (closedClockElements.size() > 1) {
System.out.println("Closed");
}
else {
System.out.println("Open");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.