Selenium程序无论我使用什么元素查询类型都返回NoSuchElementException?

huangapple go评论94阅读模式
英文:

Selenium program returning NoSuchElementException no matter what element query type I use?

问题

以下是您提供的代码的翻译部分:

我有一个股票数据网站我正在尝试使用Selenium解析数据我觉得我离成功很近但我的代码中有些问题导致程序返回了NoSuchElementException异常我可以在Chrome开发者控制台中使用以下方式通过JS查询页面https://www.cnbc.com/quotes/?symbol=.DJI)获取所需元素:

    document.getElementsByClassName("last original ng-binding")

然而我在基于Java的Selenium程序中使用类名查找元素时返回了该异常为什么在我使用与JS查询相同的类名时会出现这种情况呢我还尝试过使用xpath和css进行类似的查询但也出现了类似的错误以下是我的代码

    // 基于Java 1.7开发,以适应Selenium的兼容性要求

    // 导入包
    import java.io.File;
    import java.util.Scanner;

    import org.openqa.selenium.By;
    import org.openqa.selenium.By.ByClassName;
    import org.openqa.selenium.InvalidArgumentException;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Tester {
	
        // 实例化常用变量
        WebDriver driver;
        String url;
        Scanner input;
        boolean error;
        int uses = 0;

        public void invokeBrowser() {
            try {
                // 指定Selenium使用Chrome Driver文件
                File file = new File("C:\\Users\\zrr81\\eclipse-workspace\\WebScraper\\Selenium\\chromedriver.exe");
                System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
                 
                // 初始化Chrome驱动程序并执行维护功能
                driver = new ChromeDriver();
                driver.manage().deleteAllCookies();
                uses++;
                 
                // 执行parseData代码
                parseData();
                 
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
             
        // 尝试连接,捕获拼写错误/异常
        public void parseData() {
             try {
                input = new Scanner(System.in);
                System.out.println("请输入要连接的URL:");
                String url = input.nextLine();
                 driver.get(url);
                 elementLocator();
                 
             }
             // 捕获无效网站的特定异常(例如:死链)
             catch(InvalidArgumentException e) {
                 System.out.println("这个网站不可访问:/");
             }
             // 捕获其他所有异常
             catch(Exception ex) {
                 System.out.println("请检查您的语法!");
             }
        }
         
        public void elementLocator() {
            try {
                //driver.findElement(By.linkText("DJIA</a>")).click();
                String stock = driver.findElement(By.className("last original ng-binding")).toString();
                System.out.println(stock);
            // 捕获HTML元素未找到的特定异常
            } catch (NoSuchElementException e) {
                System.out.println("未找到所选元素");
                error = true;
            // 通用异常捕获
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            finally {
                if (error==true) {
                    closeBrowser();
                }
            }
        }
        
        public void closeBrowser() {
            // 如果只有一个窗口打开,则关闭窗口
            if(uses == 1) {
                driver.close();
            }
            // 否则,关闭整个浏览器
            else {
                driver.quit();
            }
        }
        
        // 调用方法
        public static void main(String[] args) {
            Tester myObj = new Tester();
            myObj.invokeBrowser();
        }
    }

请注意,以上是您提供的代码的翻译部分,仅包括注释、变量名、方法名以及代码结构等内容。如果您需要进一步的帮助或解释,请随时提问。

英文:

I have a stock data site that I am trying to use Selenium to parse data from. I feel like I'm really close, but something in my code is causing the program to return a NoSuchElementException. I can do a JS query of the page (https://www.cnbc.com/quotes/?symbol=.DJI) using my desired element from the Chrome developer console as follows:

document.getElementsByClassName("last original ng-binding")

However, doing a similar query in my Java-based Selenium program to find the element by class name returns this exception. Why that be when I'm using the same class name as the JS query? I've tried doing queries by xpath and css as well with a similar error. Here's my code I have:

//Built in Java 1.7 due to Selenium compatabilities
//Import packages
import java.io.File;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ByClassName;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Tester {
//Instantiate common variables
WebDriver driver;
String url;
Scanner input;
boolean error;
int uses = 0;
public void invokeBrowser() {
try {
//Point Selenium to Chrome Driver file
File file = new File("C:\\Users\\zrr81\\eclipse-workspace\\WebScraper\\Selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
//Initialize Chrome driver and perform maintenance functions
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
uses ++;
//Execute parseData code
parseData();
} catch (Exception e) {
e.printStackTrace();
}
}
//Try to connect, include catch for typos/errors
public void parseData() {
try {
input = new Scanner(System.in);
System.out.println("Enter the url you would like to connect to: ");
String url = input.nextLine();
driver.get(url);
elementLocator();
}
//Specific catch for an invalid site (e.g. a dead link)
catch(InvalidArgumentException e) {
System.out.println("He's dead Jim! :/");
}
//Catch for all other exceptions
catch(Exception ex) {
System.out.println("Check your syntax partner!");
}
}
public void elementLocator() {
try {
//driver.findElement(By.linkText("DJIA</a>")).click();
String stock = driver.findElement(By.className("last original ng-binding")).toString();
System.out.println(stock);
//Catch specific exception for html element not found
} catch (NoSuchElementException e) {
System.out.println("Selected element not found");
error = true;
//General exception catch
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (error==true) {
closeBrowser();
}
}
}
public void closeBrowser() {
//If only 1 window is open, close the window
if(uses == 1) {
driver.close();
}
//Otherwise, close the whole browser
else {
driver.quit();
}
}
//Invoke methods
public static void main(String[] args) {
Tester myObj = new Tester();
myObj.invokeBrowser();
}
}

答案1

得分: 1

NoSuchElement exception在运行时出现,表示网页上不存在要处理的元素。此外,您代码中的findElement方法有误。请参考以下代码从您的网页中提取23,433.57进行打印。

WebElement TxtBoxContent = driver.findElement(By.cssSelector("td > .last:nth-child(1)"));
System.out.println("Text " + TxtBoxContent.getText());

Selenium程序无论我使用什么元素查询类型都返回NoSuchElementException?

英文:

NoSuchElement exception occurs when element is not present on the web page for procession during Runtime. Also , your findElement is wrong in your code. Please refer below code to print 23,433.57 from your webpage.

WebElement TxtBoxContent = driver.findElement(By.cssSelector("td > .last:nth-child(1)"));
System.out.println("Text " +TxtBoxContent.getText());

Selenium程序无论我使用什么元素查询类型都返回NoSuchElementException?

huangapple
  • 本文由 发表于 2020年4月9日 05:33:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/61110388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定