【问题标题】:Change url in python在python中更改网址
【发布时间】:2020-11-11 14:28:00
【问题描述】:

如何更改此网址中的 activeOffset?我正在使用 Python 和 while 循环

https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&orderBy=kh&orderDirection=ASC

首先应该是 10,然后是 20,然后是 30 ...

我尝试了 urlparse 但我不明白如何增加数字

谢谢!

【问题讨论】:

    标签: python url urlparse


    【解决方案1】:

    如果这是一个固定的网址,您可以在网址中写上activeOffset={},然后用format{}替换为具体的数字:

    url = "https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset={}&orderBy=kh&orderDirection=ASC"
    
    for offset in range(10,100,10):
      print(url.format(offset))
    

    如果您无法修改 URL(因为您从程序的其他部分获取它作为输入),您可以使用正则表达式将出现的 activeOffset=... 替换为所需的数字 (reference):

    import re
    
    url = "https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&orderBy=kh&orderDirection=ASC"
    
    query = "activeOffset="
    pattern = re.compile(query + "\\d+") # \\d+ means any sequence of digits
    
    for offset in range(10,100,10):
      # Replace occurrences of pattern with the modified query
      print(pattern.sub(query + str(offset), url))
    

    如果要使用urlparse,可以将之前的方法应用到urlparse返回的fragment部分:

    import re
    
    from urllib.parse import urlparse, urlunparse
    
    url = "https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&orderBy=kh&orderDirection=ASC"
    
    query = "activeOffset="
    pattern = re.compile(query + "\\d+") # \\d+ means any sequence of digits
    
    parts = urlparse(url)
    
    for offset in range(10,100,10):
      fragment_modified = pattern.sub(query + str(offset), parts.fragment)
      parts_modified = parts._replace(fragment = fragment_modified)
      url_modified = urlunparse(parts_modified)
      print(url_modified)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 2018-11-29
      • 2012-01-22
      • 2016-11-17
      相关资源
      最近更新 更多