杰瑞科技汇

Python中如何获取当前URL?

Of course! Getting the current URL in Python depends heavily on where your code is running.

Python中如何获取当前URL?-图1
(图片来源网络,侵删)

Here’s a breakdown of the most common scenarios, from the simplest web scraping to building your own web application.


In a Web Browser (Client-Side JavaScript)

This is the most frequent point of confusion. If you're running Python code in a browser (like with PyScript or Brython), you're actually using JavaScript. The syntax is different.

// Get the full URL of the current page
const currentUrl = window.location.href;
console.log("Full URL:", currentUrl);
// Get only the path (e.g., "/docs/getting-started")
const path = window.location.pathname;
console.log("Path:", path);
// Get the domain (e.g., "developer.mozilla.org")
const domain = window.location.hostname;
console.log("Domain:", domain);

Important: If you see window.location in a Python context, it's almost certainly a mistake or a misunderstanding of the environment.


In a Web Scraping Script (e.g., using Selenium or Playwright)

When you use a browser automation tool, you are controlling a web browser. The "current URL" is the URL of the page that the browser is currently viewing.

Python中如何获取当前URL?-图2
(图片来源网络,侵删)

Using Selenium

Selenium is the most popular library for this.

First, install Selenium:

pip install selenium

Example Code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
# Setup the WebDriver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
try:
    # Navigate to a website
    driver.get("https://www.python.org")
    # Get the current URL from the browser
    current_url = driver.current_url
    print(f"Current URL: {current_url}")
    # Click a link to navigate to a new page
    about_link = driver.find_element(By.LINK_TEXT, "About")
    about_link.click()
    # Get the new current URL
    new_url = driver.current_url
    print(f"New URL after clicking: {new_url}")
finally:
    # Always close the browser
    driver.quit()

Key Point: driver.current_url gives you the URL of the page the browser is currently on.

Python中如何获取当前URL?-图3
(图片来源网络,侵删)

In a Web Framework (Server-Side)

If you are building a web application with a framework like Flask or Django, the concept of a "current URL" is about the URL of the incoming request that the server is processing.

Using Flask

In Flask, the request object contains all information about the incoming HTTP request.

First, install Flask:

pip install Flask

Example Code (app.py):

from flask import Flask, request
app = Flask(__name__)
@app.route('/my-page')
def my_page():
    # request.url gives the full URL of the request
    full_url = request.url
    print(f"Full Request URL: {full_url}")
    # request.path gives only the path part of the URL
    path = request.path
    print(f"Request Path: {path}")
    # request.host gives the host (domain:port)
    host = request.host
    print(f"Request Host: {host}")
    return f"The server received a request for: {full_url}"
if __name__ == '__main__':
    app.run(debug=True)

How to run and test:

  1. Save the code as app.py.
  2. Run it from your terminal: python app.py.
  3. Open your web browser and go to http://127.0.0.1:5000/my-page.
  4. Check your terminal (or the browser console if you have JavaScript logging there). You will see the printed URLs.

Using Django

Django has a similar concept, accessible through the request object passed to your view functions.

Example Code (in a views.py file):

from django.http import HttpResponse
def my_view(request):
    # request.build_absolute_uri() is the most reliable way to get the full URL
    full_url = request.build_absolute_uri()
    print(f"Full Request URL: {full_url}")
    # request.path gives only the path part
    path = request.path
    print(f"Request Path: {path}")
    return HttpResponse(f"The server received a request for: {full_url}")

In a Standard Python Script (Standalone)

In a regular .py script that is not part of a web application or browser automation, there is no concept of a "current URL". The script runs independently without any context of a web page.

If you need to get the URL of the script's file location, you can use the __file__ special variable.

import os
# Get the path of the script file
script_path = os.path.abspath(__file__)
print(f"Path to this script: {script_path}")
# Get the directory of the script
script_dir = os.path.dirname(script_path)
print(f"Directory of this script: {script_dir}")

Summary Table

Environment How to Get the URL Example Code
Browser (Client-Side) JavaScript window.location.href
Web Scraping (Selenium) Selenium WebDriver object driver.current_url
Web Framework (Flask) Flask's request object request.url or request.path
Web Framework (Django) Django's request object request.build_absolute_uri() or request.path
Standalone Python Script No concept of a "current URL" Use __file__ to get the script's file location.

To get the best answer, you should always specify where your Python code is running.

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