在python中如何在#之后从URL获取参数

2024-04-23 18:02:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从#之后的URL获取参数?你知道吗

示例:

http://localhost/addAccount/#code=qwerty

我试过使用url = request.pathurl.spit('/'),但不起作用,因为request.path不读取url中#之后的字符串。你知道吗


Tags: path字符串localhosthttpurl示例参数request
2条回答

在URL中,#之后的内容称为哈希。在到达服务器(服务器端)的HTTP请求中,此数据不会传输到服务器。因此,在服务器端,无法检索它(web浏览器不在HTTP请求中发送此数据)。你知道吗

然而,在客户端,这是可能的。在Javascript中,您可以执行以下操作:

窗户。位置。散列

不要试图手动解析URL-使用stdlib^{}
函数(^{}在python2上):

from urllib.parse import urlparse  # from urlparse import urlparse on py2
scheme = urlparse('http://localhost/addAccount/#code=qwerty')
print(scheme.fragment)

打印输出:

code=qwerty

不幸的是,您无法从服务器端获得url的fragement(在#之后的数据)。AFAIK所有浏览器都不会将fragement发送到服务器(fragement只能用于客户端代码(例如javascript)。你知道吗

引用Wikipedia

When an agent (such as a Web browser) requests a web resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent processes the resource according to the document type and fragment value.[2]

相关问题 更多 >