英文:
The application is not stopped after selenium close and quit
问题
我有一个简单的网络爬虫应用程序。
```java
public static void main(String[] args) throws InterruptedException {
        File file = new File("C:/Users/Евгений/Desktop/chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.tesco.com/groceries/en-GB/shop/fresh-food/all");
        String imageUrl = driver.findElement(By.className("product-image__container"))
                .findElement(By.className("product-image")).getAttribute("src");
        System.out.println(imageUrl);
        driver.close();
        System.err.println("closed");
    }
问题是在代码执行完毕后,应用程序并没有停止。可能的问题是什么,以及正确结束Selenium应用程序的方法是什么?
<details>
<summary>英文:</summary>
I have a simple web-scraping application.
public static void main(String[] args) throws InterruptedException {
File file = new File("C:/Users/Евгений/Desktop/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.tesco.com/groceries/en-GB/shop/fresh-food/all");
    String imageUrl = driver.findElement(By.className("product-image__container"))
            .findElement(By.className("product-image")).getAttribute("src");
    System.out.println(imageUrl);
    driver.close();
    System.err.println("closed");
}
The problem is after the code is done the application is not stopped. What could be the problem and the proper way to end the selenium application?
</details>
# 答案1
**得分**: 1
将`driver.close()`更改为`driver.quit()`。这将销毁驱动程序并释放资源,不像`close()`只关闭当前窗口。
所以正常的做法是使用以下结构:
```java
try {
    // 这里是你的代码
} finally {
    if (driver != null) {
        driver.quit();
    }
}
英文:
Change driver.close() to driver.quit(). This will destroy the driver and release resources unlike close() which closes the current window.
So the normal practice would be using the construction like this:
try {
    // your code here
}finally {
    if (driver != null) {
        driver.quit();
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论