杰瑞科技汇

python ie navigate

Of course! Navigating with Internet Explorer (IE) in Python is a very specific task, and it's important to understand the context.

python ie navigate-图1
(图片来源网络,侵删)

First, a critical piece of information: Internet Explorer has been officially deprecated and is no longer supported by Microsoft. It was replaced by Microsoft Edge. For any new project, you should strongly consider using a modern browser like Chrome, Firefox, or Edge.

However, if you absolutely must automate Internet Explorer (e.g., for maintaining an old internal web application that only works in IE), you can do it using a library called selenium.

Here’s a complete guide on how to navigate with Internet Explorer using Python and Selenium.


Prerequisites

Install Selenium

This is the Python library that controls the browser.

python ie navigate-图2
(图片来源网络,侵删)
pip install selenium

Download the IE Driver

Selenium can't control IE directly. It needs a special "driver" that acts as a bridge between your Python script and the browser.

  1. Go to the official Selenium downloads page for IE: https://www.selenium.dev/documentation/webdriver/getting_started/install_ie/
  2. Download the IEDriverServer for your system (32-bit or 64-bit). Important: The bitness of the driver must match the bitness of Internet Explorer you have installed.
  3. Extract the downloaded .zip file. You will get a file named IEDriverServer.exe.
  4. Place IEDriverServer.exe in a known location. The easiest way for beginners is to put it in the same folder as your Python script. For a more robust solution, add the directory containing the .exe file to your system's PATH environment variable.

Step-by-Step Navigation Example

Let's write a Python script to open IE, navigate to a website, click a link, and print the page title.

Full Script

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.ie.service import Service
from selenium.webdriver.ie.options import Options
from selenium.common.exceptions import WebDriverException
# --- 1. Configure Internet Explorer Options ---
# This is crucial for IE compatibility
ie_options = Options()
ie_options.ignore_zoom_level = True # IE can have issues with zoom level
ie_options.introduce_flakiness_by_ignoring_security_domains = True # Useful for intranet sites
ie_options.native_events = False # Use simulated events, which are more reliable
# --- 2. Set the path to your IEDriverServer.exe ---
# If you placed the .exe in the same folder as your script, you can just use the filename.
# Otherwise, provide the full path.
# Example for Windows:
# driver_path = r"C:\path\to\your\IEDriverServer.exe"
driver_path = "IEDriverServer.exe" # Assumes it's in the same directory
# --- 3. Initialize the WebDriver Service ---
# This tells Selenium how to start the IE driver.
service = Service(executable_path=driver_path)
try:
    # --- 4. Create the IE WebDriver instance ---
    print("Launching Internet Explorer...")
    driver = webdriver.Ie(service=service, options=ie_options)
    # --- 5. Navigate to a URL ---
    print("Navigating to Google...")
    driver.get("https://www.google.com")
    # --- 6. Interact with the page ---
    # Find the search box by its NAME attribute
    search_box = driver.find_element(By.NAME, "q")
    # Type a search query
    print("Entering search query...")
    search_box.send_keys("Python Selenium")
    # Submit the form (press Enter)
    search_box.submit()
    # Wait for the results page to load
    print("Waiting for search results...")
    time.sleep(3) # A simple wait, in a real script you'd use an explicit wait
    # --- 7. Get information from the page ---
    # Get the title of the current page
    page_title = driver.title
    print(f"Page Title is: {page_title}")
    # --- 8. Navigate to another page ---
    print("Navigating to the Selenium homepage...")
    driver.get("https://www.selenium.dev/")
    # Get the new title
    new_title = driver.title
    print(f"New Page Title is: {new_title}")
    # --- 9. Go Back ---
    print("Going back to the search results...")
    driver.back()
    back_title = driver.title
    print(f"Title after going back: {back_title}")
    # --- 10. Go Forward ---
    print("Going forward to the Selenium homepage...")
    driver.forward()
    forward_title = driver.title
    print(f"Title after going forward: {forward_title}")
    # --- 11. Refresh the page ---
    print("Refreshing the page...")
    driver.refresh()
    refresh_title = driver.title
    print(f"Title after refresh: {refresh_title}")
except WebDriverException as e:
    print(f"An error occurred: {e}")
    print("Please ensure:")
    print("1. Internet Explorer is installed on your machine.")
    print("2. The bitness (32/64-bit) of IEDriverServer.exe matches your IE installation.")
    print("3. You have closed all other instances of Internet Explorer.")
    print("4. The path to IEDriverServer.exe is correct.")
finally:
    # --- 12. Close the browser ---
    print("Closing the browser.")
    if 'driver' in locals():
        driver.quit()

Explanation of Key Navigation Methods

Method Description Example
driver.get(url) Navigates to a new URL. This is the primary way to open a webpage. driver.get("https://www.bing.com")
driver.current_url Gets the current URL of the loaded page as a string. print(driver.current_url)
driver.title Gets the title of the current page as a string. print(driver.title)
driver.back() Simulates clicking the browser's back button. driver.back()
driver.forward() Simulates clicking the browser's forward button. driver.forward()
driver.refresh() Reloads the current page. driver.refresh()
driver.close() Closes the current browser window. If it's the only window, the driver session ends. driver.close()
driver.quit() Closes all browser windows and ends the WebDriver session. This should always be used in a finally block to clean up resources. driver.quit()

Important Considerations and Troubleshooting

Automating IE is notoriously difficult. Here are the most common issues and their solutions:

  1. "The path to the driver executable must be set"

    python ie navigate-图3
    (图片来源网络,侵删)
    • Cause: Selenium can't find IEDriverServer.exe.
    • Solution: Make sure the executable_path in the Service object is correct. If you put the .exe in your script's folder, just "IEDriverServer.exe" should work. Otherwise, use the full path.
  2. "Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones."

    • Cause: This is the most common IE error. It means your browser's "Protected Mode" (found in Internet Options -> Security) is turned on for some zones and off for others. They must all be the same (either all on or all off).
    • Solution:
      1. Open Internet Explorer.
      2. Go to Tools (or the gear icon) -> Internet Options.
      3. Click on the Security tab.
      4. For each zone (Internet, Local intranet, Trusted sites, Restricted sites), ensure the "Enable Protected Mode" checkbox is checked for all or unchecked for all. All four must be the same.
      5. Click Apply and OK.
  3. "Unexpected error launching Internet Explorer. Browser zoom level was set to 100%"

    • Cause: Selenium requires the browser's zoom level to be set to 100%.
    • Solution:
      1. Hold down Ctrl and use your mouse wheel to zoom in and out.
      2. Or, in Internet Options -> Advanced, look for a setting related to zoom.
      3. Best Solution (in code): Use the ie_options.ignore_zoom_level = True option as shown in the example above. This tells Selenium not to worry about the zoom level.
  4. "The IE browser window opens but immediately closes."

    • Cause: Often, another instance of IE is already open. Selenium cannot reliably control a browser instance that it didn't start itself.
    • Solution: Before running your script, manually close all open Internet Explorer windows.

Modern Alternative: Use Microsoft Edge

Since IE is dead, the best practice is to use its modern successor, Microsoft Edge, which is now based on the same Chromium engine as Google Chrome. The code is almost identical, but much more stable and reliable.

Here is how you would modify the script for Edge:

# pip install selenium
# Make sure you have Microsoft Edge installed. Selenium will automatically download the correct driver.
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
# No need to download a driver! Selenium manages it.
# Just provide the msedgedriver path if you want to use a local version.
# Otherwise, Selenium will handle it automatically.
driver_path = "msedgedriver.exe" # Optional
try:
    # For Selenium 4.6.0+, you can just use a WebDriverManager or let it auto-download
    # This is the simplest way:
    driver = webdriver.Edge()
    print("Navigating to Google with Edge...")
    driver.get("https://www.google.com")
    print(f"Page Title is: {driver.title}")
finally:
    driver.quit()

This Edge approach is far simpler and the recommended path for any new automation work.

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