I have many repeated codes with slightly different numbers. I'm trying to shorten my codes
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get (url2)
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[2])
driver.get (url3)
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[3])
driver.get (url4)
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[4])
driver.get (url5)
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[5])
driver.get (url6)
I've tried this
def opentab(num):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[{num-1}])
driver.get (url{num})
But i'm getting error, "SyntaxError: invalid syntax"
I'm still very new to python. Any help would be much appreciated.
These are my URLs
url2 = "https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno=2"
url3 = "https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno=3"
url4 = "https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno=4"
url5 = "https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno=5"
CodePudding user response:
Define your base url
first and then use python format()
function and pass the value.
url="https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno={}"
def opentab(num,url):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[num-1])
driver.get (url.format(num))
opentab(2,url)
opentab(3,url)
opentab(4,url)
opentab(5,url)
you can use the for loop as well.
url="https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno={}"
def opentab(num,url):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[num-1])
print(url.format(num))
driver.get (url.format(num))
for i in range(2,6):
opentab(i,url)
CodePudding user response:
You can use function like this
def opentab(driver, idx, url):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[idx])
driver.get(url)
opentab(driver, 1, url2)
opentab(driver, 2, url3)
opentab(driver, 3, url4)
opentab(driver, 4, url5)
opentab(driver, 5, url6)
Or you can also use driver globally