【问题标题】:How to change Querystring value in Python? [closed]如何在 Python 中更改查询字符串的值? [关闭]
【发布时间】:2020-11-23 15:58:54
【问题描述】:

有人可以帮我如何更改 URL 中的查询字符串值吗?

这里是链接示例

示例:1 https://www.flipkart.com/footwear/paragon~brand/pr?affid=RANDOMVALUE&sort=price_asc&sid=osp

示例:2 https://www.flipkart.com/mens-footwear/pr?marketplace=FLIPKART&rwua=175f4d7321d&cpvp=1606130545181&nozq=25d72e9a2dc7&sort=price_asc&sid=osp%2Ccil&rvop=1606130052551&ysl=&p%5B%5D=facets.discount_range_v1%255B%255D%3D70%2525%2Bor%2Bmore&p%5B%5D=facets.fulfilled_by%255B%255D%3DFlipkart%2BAssured&p%5B%5D=facets.brand%255B%255D%3DLotto&p%5B%5D=facets.availability%255B%255D%3DInclude%2BOut%2Bof%2BStock&ozc=tda&affid=RANDOMVALUE

我想更改查询字符串 affid= 的值,此查询字符串以 ?affid=RANDOMVALUE&affid=RANDOMVALUE

开头>

这个查询字符串有任何随机值。我想用我的值替换它。

我尝试过使用furl

这是我尝试过的代码

 LIST_OF_QUERY_PARAMETERS_TO_REMOVE = ['tag', 'affid','affExtParam1','affExtParam2']
 result = furl.furl(full_url)
 final_url = result.remove(LIST_OF_QUERY_PARAMETERS_TO_REMOVE).url

通过上面的代码,我得到了以下结果。

'https://www.flipkart.com/footwear/paragon~brand/pr?sort=price_asc&sid=osp'

有没有更好的方法来替换 URL 中特定查询字符串的值?

【问题讨论】:

  • 为什么有人反对这个问题?这有什么问题?
  • 您想将affid=AnyValue 替换为affid=MyValue,并保持URL 的其余部分不变?
  • @MartinKleiven 是的

标签: python python-3.x python-requests


【解决方案1】:

假设affid 没有出现在字符串中的任何其他位置,但您希望它出现在您想要的位置,您可以简单地使用正则表达式。无需实际操作 URL 和任何复杂的事情。只需用字符串中的[&?]affid= 模式替换即可。

import re


def replacer(match):
    prefix = match.group(1)
    infix = "MyValue"
    suffix = match.group(3)

    # could also use f-strings: f'{prefix}{infix}{suffix}'
    # if you are on Python >= 3.6
    result = '{}{}{}'.format(prefix, infix, suffix)
    return result

def replace_affid(url, suffix):
    pattern = r'(.*[?&]affid=)(\w+)(&.*)'
    return re.sub(pattern, replacer, url)



a = "https://www.flipkart.com/footwear/paragon~brand/pr?affid=RANDOMVALUE"
b = "https://www.flipkart.com/mens-footwear/pr?marketplace=FLIPKART&affid=RANDOMVALUE"
print(replace_affid(a, "MyValue"))
print(replace_affid(b, "MyValue"))

【讨论】:

  • 哦,我是多么愚蠢!为什么我没有考虑正则表达式。谢谢!!
猜你喜欢
  • 2011-05-01
  • 2012-03-20
  • 1970-01-01
  • 2016-10-29
  • 2017-02-27
  • 1970-01-01
  • 2014-07-10
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多