簡體   English   中英

使用python從瀏覽器獲取當前URL

[英]Get current URL from browser using python

我正在運行一個 HTTP 服務器,它根據瀏覽器 URL 中的尺寸提供位圖,即localhost://image_x120_y30.bmp 我的服務器在無限循環中運行,我想在用戶請求 BITMAP 時隨時獲取 URL,最后我可以從 URL 中提取圖像尺寸。

這里問的問題:

如何在python網頁中獲取當前URL?

沒有解決我的問題,因為我在無限循環中運行,我想繼續獲取當前 URL,以便我可以將請求的 BITMAP 交付給用戶。

如果使用 Selenium 進行網頁導航:

from selenium import webdriver
driver = webdriver.Firefox()
print (driver.current_url)

您可以通過執行path_info = request.META.get('PATH_INFO') http_host = request.META.get('HTTP_HOST')來獲取當前 url。 您可以添加這兩個以獲得完整的網址。 基本上 request.META 會返回一個包含大量信息的字典。 你可以試試看。

我剛剛解決了一個類似的類問題。 我們一直在使用 Splinter 瀏覽頁面(您需要下載 Splinter 和 Selenium)。 當我瀏覽頁面時,我需要定期拉出我當前所在頁面的 url。 我使用命令 new_url = browser.url 來做到這一點 下面是我的代碼示例。

我使用以下代碼執行此操作。

##import dependencies
from splinter import browser
import requests


## go to original page 
browser.visit(url)

## Loop through the page associated with each headline
for headline in titles:
    print(headline.text)
    browser.click_link_by_partial_text(headline.text)
## Now that I'm on the new page, I need to grab the url
    new_url = browser.url
    print(new_url)
## Go back to original page
    browser.visit(url)

以下是我在 Django 中使用的解決方案。

例如,。 如果瀏覽器網址是https://www.example.com/dashboard

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

frontend_url = request.META.get('HTTP_REFERER')
url = urlparse(frontend_url)
print (url)
# ParseResult(scheme='https', netloc='example.com', path='/dashboard', params='', query='', fragment='')

您可以使用requests模塊:

import requests


link = "https://stackoverflow.com"
data = requests.request("GET", link)
url = data.url

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM