【问题标题】:Parsing through the path of an URL通过 URL 的路径解析
【发布时间】:2021-06-23 04:48:23
【问题描述】:

我正在处理来自 tweeter 的数据,我正在尝试获取域以及 .com 之后路径中的第一个元素。例如,我有一个网址:

'https://www.facebook.com/estebanfarfanr/videos/1281699612020348/'

在这种情况下,我所有的数据集都以 Facebook 作为域。我需要的是包含域的 URL 链接,在这种情况下是用户 ID。因此,我需要留下:

https://www.facebook.com/estebanfarfanr/

并删除 URL 的其余部分。如果有人有建议,我还没有找到一个简单的方法。

【问题讨论】:

  • 根据您的要求使用正则表达式解析字符串。

标签: python parsing url


【解决方案1】:

要在python中操作url,可以使用the urllib.parse module

from urllib.parse import urlsplit, urlunsplit

def first_level_url(url: str) -> str:
    """Return the url trimmed after the first path level."""
    split_url = urlsplit(url)
    path_parts = split_url.path.split("/")  # The first level of the path

    # Edit the path, trimming everything after the first level
    # beyond root, eg: /first/second/third/ -> /first/
    new_path = "/".join(path_parts[:2]) + "/"

    new_url = split_url._replace(
       # Replace the original path with our edit
        path=new_path,
        # Remove the query string if it exists -- ?example=query
        query="",
        # Remove the fragment if it exists -- #example:fragment
        fragment="",
    )

    # Put the url back together with changes
    return urlunsplit(new_url)

以下是它如何与您的示例网址一起使用:

>>> first_level_url(
        "https://www.facebook.com/estebanfarfanr/videos/1281699612020348/"
    )
'https://www.facebook.com/estebanfarfanr/'

>>> first_level_url("https://stackoverflow.com/questions/68093654/")
'https://stackoverflow.com/questions/'

# It will remove query strings and fragments too
>>> first_level_url(
        "https://github.com/blackrobot/foo/bar/?hello=world#lorem:ipsum"
    )
'https://github.com/blackrobot/'

【讨论】:

  • 为什么我们需要返回 urlunsplit(new_url) 而不仅仅是 new_url。 ?
  • 就这样你现在我使用了它,它除了我列表中的一些 url 仍然输出如下内容:“facebook.com/1133685943410489/?sfnsn=mo&d=n&vh=e”我在列表中看到了所有这些,看起来就像所有没有被修剪的链接一样 / 模式如何?身份证后。但总体而言,对于我上面的问题,我只是想了解我们需要使用 unsplit 来返回对象的原因。
  • @Wara 我已经更新了first_level_url 函数以删除查询字符串(以及片段)。该函数使用urlunsplit(...),因为urlsplit(...) 返回的值是tuple,而不是str。尝试在python终端中玩urlsplit(...),你就会明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 2015-06-09
  • 2014-04-03
  • 2015-11-25
  • 1970-01-01
相关资源
最近更新 更多