如何从url路径获取参数?

2024-04-20 11:51:45 发布

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

介绍性标签:pythonpython-3.xurlparametersurlopen

使用的语言:Python 3.x

使用的模块:urlopen|urllib.request请求

状态:尚未解决

问题描述:

我有网址:

 http://mapy.cz/#mm=TTtP@x=133054720@y=135947904@z=13

它会将我(在web浏览器中)重定向到另一个url:

 https://mapy.cz/zakladni?x=14.412346408814274&y=50.08612581835152&z=13

我想从路径中得到参数xy。你知道吗

 x = 14.412346408814274
 y = 50.08612581835152

(地理坐标以十进制表示)。

当我使用:

 from urllib.request import urlopen

 url = "http://mapy.cz/#mm=TTtP@x=133168128@y=133141248@z=13"
 print(urlopen(url).url)

它会还给我:

 https://mapy.cz/

当我使用:

with urlopen(url) as conn:
    newUrl = conn.geturl()        
    print (newUrl)

它会还给我:

 https://mapy.cz/        

当我使用:

with urlopen(url) as conn:
    print (conn.info())

它会还给我:

Server: nginx
Date: Sun, 03 Jun 2018 23:24:31 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Cache-Control: max-age=0
Expires: Sun, 03 Jun 2018 23:24:31 GMT
Strict-Transport-Security: max-age=31536000

当我使用:

with urlopen(url) as conn:
    print (conn.__dict__)

它会还给我:

{'fp': <_io.BufferedReader name=1404>, 'debuglevel': 0, '_method': 'GET', 'headers': <http.client.HTTPMessage object at 0x000000000DD48518>, 'msg': 'OK', 'version': 11, 'status': 200, 'reason': 'OK', 'chunked': True, 'chunk_left': None, 'length': None, 'will_close': True, 'code': 200, 'url': 'https://mapy.cz/'}

斜杠后面没有提到参数/路径。 既不是原始url,也不是以下url。你知道吗

当我使用来自What is the quickest way to HTTP GET in Python?的代码时:

import urllib.request
contents = urllib.request.urlopen("url").read()

它会还给我:

'raw html...'

我不想打开/下载html并从html中挖掘这些参数。你知道吗


Tags: httpshttpurl参数requesthtmlaswith
1条回答
网友
1楼 · 发布于 2024-04-20 11:51:45

如果您使用requests(您应该这样做),下面是针对特定URL的解决方案:

import requests

URL = 'http://mapy.cz/#mm=TTtP@x=133054720@y=135947904@z=13'

response = requests.get(URL)

if response.history:
    print("Request was redirected")
    for resp in response.history:
        print((resp.status_code, resp.url,))
        # getting x, y and z
        parts = resp.url.split('@')
        x = parts[1].split('=')[1]
        y = parts[2].split('=')[1]
        z = parts[3].split('=')[1]
        print("X {} Y {} Z {}".format(x, y, z))

    print("Final destination:")
    print((response.status_code, response.url,))
else:
    print("Request was not redirected")

相关问题 更多 >