乐闻世界logo
搜索文章和话题

How to fetch the current page URL in Selenium?

1个答案

1

Retrieving the current page URL in Selenium is a common operation that can be achieved by accessing the current_url attribute of the WebDriver object.

Steps

  1. Import the Selenium library: Ensure you have installed the Selenium library and imported the necessary components in your script.
  2. Launch the WebDriver: Start the appropriate WebDriver based on your browser type (e.g., Chrome, Firefox).
  3. Navigate to the target webpage: Use the get method to open the specified URL in the browser.
  4. Retrieve the current page URL: Access the current_url attribute of the WebDriver object to obtain it.
  5. Print or use the URL: You can print the retrieved URL or utilize it for further processing.

Example Code

python
from selenium import webdriver # Create a WebDriver instance, here using Chrome driver = webdriver.Chrome() try: # Navigate to the webpage driver.get("http://example.com") # Retrieve the current page URL current_url = driver.current_url print("Current page URL is:", current_url) finally: # Close the browser driver.quit()

Explanation

In this example, we first import the webdriver module, then create a Chrome WebDriver instance. We navigate to "http://example.com" using the get method, retrieve the current URL via the current_url attribute, and print it. Finally, we use quit to ensure the browser is properly closed.

By following this approach, you can easily retrieve and utilize the current page URL in automated testing or web scraping processes.

2024年8月14日 00:51 回复

你的答案