【问题标题】:Python Get Tags from URLPython 从 URL 获取标签
【发布时间】:2014-06-13 15:06:18
【问题描述】:

我有以下网址:

http://google.com/sadfasdfsd$AA=mytag&SS=sdfsdf

在 Python 中从字符串 ~$AA=mytag&~ 获取 mytag 的最佳方法是什么?

【问题讨论】:

  • 您确定该 URL 正是您所拥有的吗?还是您的意思是http://google.com/sadfasdfsd?AA=mytag&SS=sdfsdf? 而不是$)?
  • 我很好奇。当前的 3 个答案都建议使用正则表达式来执行此操作。当 python 有可以解析查询字符串的模块(例如 urlparse:docs.python.org/2/library/urlparse.html)时,为什么要这样做?当然,正则表达式的答案更短,但不一定更容易理解。

标签: python regex python-2.7


【解决方案1】:

试试这个,

>>> import re
>>> str = 'http://google.com/sadfasdfsd$AA=mytag&SS=sdfsdf'
>>> m = re.search(r'.*\$AA=([^&]*)\&.*', str)
>>> m.group(1)
'mytag'

在正则表达式中$& 有特殊含义,因此您必须转义这些字符以告诉python 解释器这些字符是文字​​$&

【讨论】:

    【解决方案2】:

    使用这个正则表达式=(.+)&

    import re
    regex = "=(.+)&"
    print re.findall(regex,"http://google.com/sadfasdfsd$AA=mytag&SS=sdfsdf")[0]
    

    【讨论】:

      【解决方案3】:

      要检索$AA 之后的mytag,您可以使用这个简单的正则表达式(参见demo):

      (?<=\$AA=)[^&]+
      

      在 Python 中:

      match = re.search(r"(?<=\$AA=)[^&]+", subject)
      

      解释正则表达式

      (?<=                     # look behind to see if there is:
        \$                     #   '$'
        AA=                    #   'AA='
      )                        # end of look-behind
      [^&]+                    # any character except: '&' (1 or more times
                               # (matching the most amount possible))
      

      【讨论】:

        【解决方案4】:

        我只是要把这个扔出去,以表明还有其他方法可以做到这一点:

        import urlparse
        
        url = "http://google.com/sadfasdfsd?AA=mytag&SS=sdfsdf"
        query = urlparse.urlparse(url).query # Extract the query string from the full URL
        parsed_query = urlparse.parse_qs(query) # Parses the query string into a dict
        
        print parsed_query["AA"][0]
        # mytag
        

        有关 urlparse 模块的文档,请参见此处:https://docs.python.org/2/library/urlparse.html

        注意parse_qs 返回一个列表,所以我们使用[0] 来获得第一个结果。

        另外,我假设问题有错字,并修改了网址,使其代表传统的查询字符串。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-07
          • 2021-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-10
          相关资源
          最近更新 更多