Home > Net >  replacing the url
replacing the url

Time:11-13

Just like the title says, how do I write the code in python if I want to replace a part of the URL.

For this example replacing a specific part by 1, 2, 3, 4 and so on for this link (https://test.com/page/1), then doing something on said page and going to the next and repeat

so "open url > click on button or whatever > replace link by the new link with the next number in order"

(I know my code is a mess I am still a newbie, but I am trying to learn and I am adding whatever mess I've wrote so far to follow the posting rules)

PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()

get = 1
url = "https://test.com/page/{get}"

while get < 5:
    driver.get(url)
    time.sleep(1)
    driver.find_element_by_xpath("/html/body/div/div/div[2]/form/section[3]/input[4]").click()
    get = get   1
    driver.get(url)
    driver.close()

CodePudding user response:

get = 1
url = f"https://test.com/page/{get}"

while get < 5:
    
    driver.get(url)
    driver.find_element_by_xpath("/html/body/div/div/div[2]/form/section[3]/input[4]").click()
    print(get)
    print(url)
    get =1
    url =  f"https://test.com/page/{get}"
    

To simply update url in a loop.

Outputs

1
https://test.com/page/1
2
https://test.com/page/2
3
https://test.com/page/3
4
https://test.com/page/4

CodePudding user response:

Use the range() function and use String interpolation as follows:

for i in range(1,5):
    print(f"https://test.com/page/{i}")
    driver.get(f"https://test.com/page/{i}")
    driver.find_element_by_xpath("/html/body/div/div/div[2]/form/section[3]/input[4]").click()

Console Output:

https://test.com/page/1
https://test.com/page/2
https://test.com/page/3
https://test.com/page/4
  • Related