杰瑞科技汇

Python Selenium如何操作IE浏览器?

Of course. Here is a comprehensive guide on using Python with Selenium to control Internet Explorer (IE).

Python Selenium如何操作IE浏览器?-图1
(图片来源网络,侵删)

Important Warning: Internet Explorer is Deprecated and Not Recommended

Before we dive in, it's crucial to understand that Microsoft officially deprecated and discontinued Internet Explorer in 2025. It has been replaced by Microsoft Edge, which is based on the Chromium engine.

  • Official Support Ended: Microsoft no longer provides security updates or technical support for IE.
  • Modern Web Apps Won't Work: Many modern websites, especially those using JavaScript frameworks (React, Angular, Vue), will not function correctly or at all in IE.
  • Selenium's Stance: Selenium has officially dropped support for Internet Explorer in version 4.0 and later.

Therefore, you should only use this information for maintaining legacy applications that absolutely must be tested on an old version of IE. For all new projects, please use Microsoft Edge (Chromium), which is fully supported by modern Selenium and provides a much better, faster, and more reliable testing experience.


Step-by-Step Guide: Setting up Selenium for Internet Explorer

If you absolutely must use IE, follow these steps.

Install the Necessary Python Packages

You need selenium to control the browser and a WebDriver to act as a bridge between your script and the browser.

pip install selenium

Download the InternetExplorerDriver (IEDriverServer)

Selenium cannot control IE directly. It needs a helper executable called IEDriverServer.exe.

  1. Go to the Selenium Downloads Page: https://www.selenium.dev/downloads/
  2. Scroll down to the "Legacy Browsers" section.
  3. Find "Internet Explorer" and click the link to download the latest version (e.g., IEDriverServer_Win32_3.150.1.zip).
  4. Extract the ZIP file. You will find IEDriverServer.exe inside.

Configure Your System (This is Critical)

IE has strict security settings that will prevent the IEDriverServer from working if not configured correctly.

A. Enable "Protected Mode" (Consistent State)

This is the most common issue. Protected Mode must be ON or OFF for all zones (Internet, Local intranet, Trusted sites, Restricted sites). It's highly recommended to set them all to the same state.

  1. Open Internet Explorer.
  2. Click the Gear icon (Tools) > Internet options.
  3. Go to the Security tab.
  4. For each zone (Internet, Local intranet, Trusted sites, Restricted sites), ensure that "Enable Protected Mode" is checked (ON) for all or unchecked (OFF) for all. A mixed state will cause the driver to fail.
  5. Click Apply, then OK.

B. Disable "Enhanced Protected Mode"

  1. In the same Internet Options window, go to the Advanced tab.
  2. Scroll down to the "Security" section.
  3. Uncheck the box for "Enable Enhanced Protected Mode".
  4. Click Apply, then OK. You may need to restart IE for this to take effect.

C. Set the Zoom Level to 100%

The driver can reliably control the browser only when the zoom level is set to 100%.

  1. In Internet Explorer, click the Magnifying glass icon in the bottom-right corner.
  2. Select 100%.

Place the IEDriverServer.exe and Write the Code

You have two main options for placing the IEDriverServer.exe file:

Option A (Recommended): Place it in your Project Folder

Create a folder for your project, put the IEDriverServer.exe file inside it, and run your Python script from that same folder. This keeps everything organized.

Option B: Add it to your System's PATH

Place the IEDriverServer.exe in a directory that is already in your system's PATH environment variable (e.g., C:\Windows\System32). This allows you to run the script from any location without specifying the path to the executable.


Example Python Code

Here is a basic script to open a website, perform an action, and close the browser.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.ie.options import Options
from selenium.common.exceptions import WebDriverException
# --- Configuration ---
# Path to the IEDriverServer.exe file.
# If it's in the same folder as your script, you can just use the filename.
# If it's elsewhere, provide the full path.
# e.g., "C:/path/to/your/folder/IEDriverServer.exe"
IEDRIVER_PATH = "IEDriverServer.exe" 
# --- Main Script ---
try:
    # 1. Set up IE Options
    # It's good practice to set capabilities explicitly.
    ie_options = Options()
    ie_options.ignore_zoom_level = True  # This is a must-have for IE
    ie_options.ignore_protected_mode_settings = True # Use with caution, often needed
    ie_options.introduce_flakiness_by_ignoring_security_domains = True # Another common workaround
    # 2. Initialize the WebDriver
    print("Attempting to start Internet Explorer...")
    # The executable_path argument is deprecated in newer Selenium versions.
    # If you get a warning, try using Service object instead.
    driver = webdriver.Ie(options=ie_options, executable_path=IEDRIVER_PATH)
    # Alternative way with Service (recommended for newer Selenium versions)
    # from selenium.webdriver.ie.service import Service
    # service = Service(executable_path=IEDRIVER_PATH)
    # driver = webdriver.Ie(service=service, options=ie_options)
    print("Internet Explorer started successfully.")
    # 3. Use the WebDriver
    driver.get("https://www.bing.com")
    print(f"Page Title is: {driver.title}")
    # Example: Find the search box and type a query
    search_box = driver.find_element(By.NAME, "q")
    search_box.send_keys("Selenium with IE")
    search_box.submit()
    # Wait for results to load
    driver.implicitly_wait(5) 
    print(f"Search Results Page Title is: {driver.title}")
    # 4. Close the Browser
    print("Closing the browser.")
    driver.quit()
except WebDriverException as e:
    print(f"WebDriver Error: {e}")
    print("Please ensure that:")
    print("1. Internet Explorer is installed.")
    print("2. IEDriverServer.exe is in the correct location.")
    print("3. IE's Protected Mode is set consistently (ON for all or OFF for all).")
    print("4. IE's Zoom level is set to 100%.")
    print("5. 'Enable Enhanced Protected Mode' is OFF in IE's Advanced settings.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    if 'driver' in locals():
        driver.quit()

Common Issues and Troubleshooting

  • selenium.common.exceptions.WebDriverException: Message: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones.
    • Solution: Go to IE's Internet Options > Security tab and ensure "Enable Protected Mode" is checked (or unchecked) for all four zones.
  • selenium.common.exceptions.WebDriverException: Message: Unable to create new remote session. Please check the IEDriverServer log file for additional information.
    • Solution: This is a generic error. Check the log file generated by IEDriverServer.exe (it will be in the same directory as the .exe). The log often gives a specific reason, like the zoom level not being 100% or a security setting mismatch.
  • selenium.common.exceptions.WebDriverException: Message: 'msedgedriver.exe' needs to be in the PATH...
    • Solution: This error means Selenium is trying to start Microsoft Edge (Chromium), not Internet Explorer. Make sure you are using webdriver.Ie() and not webdriver.Edge().
  • The script hangs or is very slow.
    • Solution: IE is notoriously slow. Ensure you have ie_options.ignore_zoom_level = True. Also, be patient with time.sleep() or driver.implicitly_wait() commands, as page rendering can take much longer than in modern browsers.

The Modern Alternative: Use Microsoft Edge (Chromium)

For any new project, please switch to Edge. It's faster, more secure, and fully supported.

Install Microsoft Edge: Make sure you have a recent version of Microsoft Edge installed.

Install the msedgedriver:

  • Go to the Edge Driver download page.
  • Download the version that matches your Edge browser.
  • Extract msedgedriver.exe and place it in your project folder or system PATH.

Python Code for Edge:

from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
# Path to the msedgedriver.exe
EDGE_DRIVER_PATH = "msedgedriver.exe" 
# Set up the Service
service = Service(executable_path=EDGE_DRIVER_PATH)
# Initialize the WebDriver
driver = webdriver.Edge(service=service)
# Use the WebDriver
driver.get("https://www.google.com")
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Selenium with Edge")
search_box.submit()
# Close the browser
driver.quit()

As you can see, the code is cleaner, more reliable, and the future of browser automation with Selenium.

分享:
扫描分享到社交APP
上一篇
下一篇