【发布时间】:2020-11-11 14:28:00
【问题描述】:
如何更改此网址中的 activeOffset?我正在使用 Python 和 while 循环
首先应该是 10,然后是 20,然后是 30 ...
我尝试了 urlparse 但我不明白如何增加数字
谢谢!
【问题讨论】:
如何更改此网址中的 activeOffset?我正在使用 Python 和 while 循环
首先应该是 10,然后是 20,然后是 30 ...
我尝试了 urlparse 但我不明白如何增加数字
谢谢!
【问题讨论】:
如果这是一个固定的网址,您可以在网址中写上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)
【讨论】: