学习Selenium时遭遇java.lang.IllegalStateException错误:需设置webdriver.chrome.driver系统属性
Hey there! That error is super common when getting started with Selenium—let’s get it sorted out quickly.
Why You’re Seeing This Error
Selenium relies on the ChromeDriver executable to connect with your Chrome browser, but right now it can’t locate where you’ve saved that file. The error message is explicitly telling you to define the path to ChromeDriver using the webdriver.chrome.driver system property.
Step-by-Step Solution
Download the Correct ChromeDriver Version
- First, check your Chrome browser version (go to
chrome://settings/help). You need to download a ChromeDriver version that matches this exactly—mixing versions will cause issues. - Save the ChromeDriver executable in an easy-to-find location, like a dedicated
driversfolder in your project or a system-wide spot (e.g.,C:\driverson Windows,/usr/local/binon Mac/Linux).
- First, check your Chrome browser version (go to
Set the Driver Path in Your Code
Add this line before you initialize theChromeDriverinstance. Adjust the path to match where you saved ChromeDriver:// For Windows (use double backslashes or forward slashes) System.setProperty("webdriver.chrome.driver", "C:\\your-folder\\chromedriver.exe"); // For Mac/Linux (no .exe extension needed) // System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");Here’s your modified code with this fix included:
package seleniumPractice; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class seleniumPractice { public static void main(String[] args) { // Define path to ChromeDriver System.setProperty("webdriver.chrome.driver", "C:\\your-folder\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://google.com"); driver.quit(); } }Alternative: Add ChromeDriver to Your System PATH
If you don’t want to set the property in code every time, add the folder containing ChromeDriver to your system’sPATHenvironment variable. Once you do this, you can remove theSystem.setPropertyline entirely—Selenium will automatically find the driver.
Quick Tips
- On Windows, don’t forget to include the
.exeextension in the path. - On Mac/Linux, you may need to grant executable permissions to ChromeDriver with the command:
chmod +x /path/to/chromedriver.
内容的提问来源于stack exchange,提问作者anonymousUser

