【问题标题】:how do i replace a query with a new value in urlparse?如何在 urlparse 中用新值替换查询?
【发布时间】:2014-10-06 17:37:29
【问题描述】:

所以我有一个数据如下:

 item = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'

使用 urlparse 模块。我怎样才能用新的大小替换上面的数据,使它看起来像这样:

  item = '//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'

【问题讨论】:

    标签: python urlparse scene7


    【解决方案1】:

    这是一个根据要求使用 urlparse 的答案:

    import urllib
    import urlparse
    
    url = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'
    parts = urlparse.urlparse(url)
    query_dict = urlparse.parse_qs(parts.query)  # {'wid': ['98'], 'hei': ['98']}
    query_dict['wid'] = '360'
    query_dict['hei'] = '360'
    new_parts = list(parts)
    new_parts[4] = urllib.urlencode(query_dict)
    print urlparse.urlunparse(new_parts)
    

    【讨论】:

    • hm....我得到这个值 //s780.scene7.com/is/image/forever/301596014_001;wid=360&hei=240?hei=98&wid=98 我该如何摆脱这部分在这里 hei=98&wid=98
    【解决方案2】:

    如果 hei 和 wid 总是等于一个数,那么我们有:

     a = item[item.find('=')+1:item.find('&')] #this is the number in url (in your example it is 98
     item.replace(a, '360')   #item.replace(a, NewNumber) 
    

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      这是你想要的吗?

      item_360 = item.replace("=98","=360")
      print item_360
      '//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'
      

      我放了“=”以避免替换之前的数字(如果存在)。

      对于更复杂的替换,您可以查看regex

      所以,如果你不知道98,你可以使用正则表达式:

      import re
      item_360 = re.sub("=\d+", '=360', item)
      

      【讨论】:

      • 也许我们不知道url中的当前数字是多少!
      【解决方案4】:

      我喜欢这样做以使其易于阅读:

      from urllib.parse import urlsplit, urlunsplit, urlencode
      
      split = urlsplit(url)
      new_url = urlunsplit((
          split.scheme,
          split.netloc,
          split.path,
          urlencode(dict(hei=360, wid=360)),
          None,
      ))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 2016-12-17
        相关资源
        最近更新 更多