简体   繁体   English

在python中更改网址

[英]Change url in python

how can I change the activeOffset in this url?如何更改此 url 中的 activeOffset? I am using Python and a while loop我正在使用 Python 和一个 while 循环

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

It first should be 10, then 20, then 30 ...它首先应该是 10,然后是 20,然后是 30 ...

I tried urlparse but I don't understand how to just increase the number我试过 urlparse 但我不明白如何增加数字

Thanks!谢谢!

If this is a fixed URL, you can write activeOffset={} in the URL then use format to replace {} with specific numbers:如果这是一个固定 URL,您可以在 URL 中写入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))

If you cannot modify the URL (because you get it as an input from some other part of your program), you can use regular expressions to replace occurrences of activeOffset=... with the required number ( reference ):如果您无法修改 URL(因为您从程序的其他部分获取它作为输入),您可以使用正则表达式将出现的activeOffset=...替换为所需的数字(参考):

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))

If you want to use urlparse , you can apply the previous approach to the fragment part returned by urlparse :如果要使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM