【问题标题】:How do you extract parameters from a url that only contain slash using python?如何使用 python 从仅包含斜杠的 url 中提取参数?
【发布时间】:2021-05-04 06:46:51
【问题描述】:

我有一个网址“http://example.com/title/hello/users/123/example-1”。我想提取信息 Title: "hello", users": "123" 以及 "example-1"。如何使用 urllib 提取这些信息?我不想为此使用正则表达式。

from urllib.parse import urlparse

url = 'http://example.com/title/hello/users/123/example-1'
print(urlparse(url))

# How do i extract the parameters in the path below?
# ParseResult(scheme='http', netloc='example.com', path='/title/hello/users/123/example-1', params='', query='', fragment='')

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我试过 urlparse 但我得到的只是“/title/hello/users/123/example-1”。
  • 请发布您的代码!
  • 我现在真的没有工作代码。
  • 我可以尝试使用 split("/") 函数,但是有没有自动提取的 python 库?

标签: python url python-3.6 urllib urlparse


【解决方案1】:
from urllib.parse import urlparse

parsed = urlparse('http://example.com/title/hello/users/123/example-1')
parsed = parsed.path.split("/")

Urlparse 返回一个已解析的对象。我们可以使用这个解析器对象的路径,并用“/”分割它。结果如下:

['', 'title', 'hello', 'users', '123', 'example-1']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多