【问题标题】:How can I split a url string up into separate parts in Python?如何在 Python 中将 url 字符串拆分为单独的部分?
【发布时间】:2010-10-01 18:37:40
【问题描述】:

我决定今晚学习 python :) 我非常了解 C(在其中编写了一个操作系统),所以我不是编程的菜鸟,所以 python 中的一切似乎都很容易,但我不知道如何解决这个问题: 假设我有这个地址:

http://example.com/random/folder/path.html 现在我如何从中创建两个字符串,一个包含服务器的“基本”名称,所以在这个例子中它是 http://example.com/ 另一个包含没有最后一个文件名的东西,所以在这个例子中它是 http://example.com/random/folder/ . 我当然也知道分别找到第三个和最后一个斜杠的可能性,但也许你知道更好的方法:] 在这两种情况下都有斜杠也很酷,但我不在乎,因为它可以很容易地添加。 那么有人对此有一个好的、快速、有效的解决方案吗?还是只有“我的”解决方案,找到斜线?

谢谢!

【问题讨论】:

  • 您可能希望在代码中分享您的解决方案。
  • 明天回来告诉我们你的情况如何。我怀疑你只会用 Python 编写 C 代码,而不是真正的 Python 代码:-)。
  • 既然你提到了,你写的是哪个操作系统?
  • 您可以在此处找到用于部分拆分(即 URL、方案、域、TLD、端口和查询路径)的 Python 正则表达式:stackoverflow.com/questions/9760588/…

标签: python url parsing


【解决方案1】:

你可以使用python的库furl:

f = furl.furl("http://example.com/random/folder/path.html")
print(str(f.path))  # '/random/folder/path.html'
print(str(f.path).split("/")) # ['', 'random', 'folder', 'path.html']

要访问第一个“/”之后的单词,请使用:

str(f.path).split("/") # random

【讨论】:

    【解决方案2】:

    我没有使用 Python 的经验,但我找到了 urlparse module,它应该可以完成这项工作。

    【讨论】:

      【解决方案3】:

      非常感谢这里的其他回答者,他们通过他们给出的答案为我指明了正确的方向!

      sykora 的答案中提到的 posixpath 模块似乎在我的 Python 设置(python 2.7.3)中不可用。

      根据this article,似乎“正确”的方法是使用...

      • urlparse.urlparseurlparse.urlunparse 可用于分离和重新附加 URL 的基础
      • os.path的函数可以用来操作路径
      • urllib.url2pathnameurllib.pathname2url(使路径名操作可移植,因此可以在 Windows 等系统上运行)

      例如(不包括重新附加基本 URL)...

      >>> import urlparse, urllib, os.path
      >>> os.path.dirname(urllib.url2pathname(urlparse.urlparse("http://example.com/random/folder/path.html").path))
      '/random/folder'
      

      【讨论】:

        【解决方案4】:

        python 2.x 中的 urlparse 模块(或 python 3.x 中的 urllib.parse)将是这样做的方法。

        >>> from urllib.parse import urlparse
        >>> url = 'http://example.com/random/folder/path.html'
        >>> parse_object = urlparse(url)
        >>> parse_object.netloc
        'example.com'
        >>> parse_object.path
        '/random/folder/path.html'
        >>> parse_object.scheme
        'http'
        >>>
        

        如果你想对 url 下的文件路径做更多的工作,你可以使用 posixpath 模块:

        >>> from posixpath import basename, dirname
        >>> basename(parse_object.path)
        'path.html'
        >>> dirname(parse_object.path)
        '/random/folder'
        

        之后,您可以使用 posixpath.join 将各个部分粘合在一起。

        编辑:我完全忘记了 Windows 用户会被 os.path 中的路径分隔符阻塞。我阅读了 posixpath 模块文档,它对 URL 操作有一个特殊的参考,所以一切都很好。

        【讨论】:

        • +1 在 urlparse 上,但不要使用 os.path 来操作 .path 部分。 os.path 的处理方式因操作系统而异,而 URI 始终使用“/”作为路径部分分隔符。
        • 是的,删除 os.path 部分。也许改用 posixpath 模块。然后你就会有我的投票。
        • 啊,完全错过了那个。自从我使用 Windows 以来已经有很多年了:|。固定。
        • 为了方便参考,这里是 Py 2 的过程:import urlparse; parse_object = urlparse.urlparse(url)
        • "windows 用户会窒息......" 我喜欢把它想象成 Linux 用户会被之前的路径说明符窒息 :)
        【解决方案5】:

        如果这是您的 URL 解析范围,Python 的内置 rpartition 将完成这项工作:

        >>> URL = "http://example.com/random/folder/path.html"
        >>> Segments = URL.rpartition('/')
        >>> Segments[0]
        'http://example.com/random/folder'
        >>> Segments[2]
        'path.html'
        

        来自Pydoc,str.rpartition:

        Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself

        这意味着 rpartition 会为您进行搜索,并在您指定的字符(在本例中为 / )的最后(最右边)出现处拆分字符串。它返回一个元组,其中包含:

        (everything to the left of char , the character itself , everything to the right of char)
        

        【讨论】:

          【解决方案6】:

          在 Python 中,很多操作都是使用列表完成的。 Sebasian Dietz 提到的 urlparse 模块可以很好地解决您的特定问题,但是如果您通常对 Python 的在字符串中查找斜线的方法感兴趣,请尝试以下操作:

          url = 'http://example.com/random/folder/path.html'
          # Create a list of each bit between slashes
          slashparts = url.split('/')
          # Now join back the first three sections 'http:', '' and 'example.com'
          basename = '/'.join(slashparts[:3]) + '/'
          # All except the last one
          dirname = '/'.join(slashparts[:-1]) + '/'
          print 'slashparts = %s' % slashparts
          print 'basename = %s' % basename
          print 'dirname = %s' % dirname
          

          这个程序的输出是这样的:

          slashparts = ['http:', '', 'example.com', 'random', '文件夹', 'path.html'] 基本名称 = http://example.com/ 目录名 = http://example.com/random/folder/

          有趣的位是splitjoin、切片符号数组[A:B](包括从末端偏移的负数)以及作为奖励的字符串上的%运算符提供 printf 样式的格式。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-11-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-09-04
            • 1970-01-01
            • 2015-08-17
            相关资源
            最近更新 更多