You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python def函数简化重复Selenium代码?解决语法错误

解决Python+Selenium重复代码精简的语法错误问题

我有大量仅数字存在细微差异的重复Selenium代码,想精简代码。原代码如下:

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)

我尝试写了如下函数,但运行时出现SyntaxError: invalid syntax语法错误:

def opentab(num):
    driver.execute_script("window.open('');")
    driver.switch_to.window(driver.window_handles[{num-1}])
    driver.get (url{num})

我的URL变量定义如下:

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"

错误原因分析

你写的函数里有两个明显的语法错误:

  • driver.window_handles[{num-1}]:Python列表索引直接写表达式即可,{}是字符串格式化语法,不能用在这里,直接写num-1就合法。
  • driver.get (url{num}):Python不支持通过url{num}这种方式拼接变量名,这种写法不符合语法规范。

解决方案

方案1:适配已定义的URL变量

如果要保留已定义的url2、url3等变量,可以通过globals()函数根据变量名字符串获取对应变量值,修改后的函数如下:

def opentab(num):
    driver.execute_script("window.open('');")
    # 直接用num-1作为列表索引
    driver.switch_to.window(driver.window_handles[num-1])
    # 构造变量名字符串,从全局命名空间中获取变量
    url_var = globals()[f"url{num}"]
    driver.get(url_var)

调用示例:

# 批量打开url2到url5对应的标签页
for num in range(2, 6):
    opentab(num)

方案2:直接构造URL(更优)

观察你的URL可以发现,仅raceno参数的数字不同,完全不需要定义多个重复的URL变量,直接动态构造URL更简洁:

def opentab(raceno):
    driver.execute_script("window.open('');")
    # 用[-1]直接获取最新打开的窗口,无需计算索引
    driver.switch_to.window(driver.window_handles[-1])
    # 构造目标URL
    base_url = "https://bet.hkjc.com/racing/pages/odds_wp.aspx?lang=en&date=2022-09-21&venue=HV&raceno={}"
    target_url = base_url.format(raceno)
    driver.get(target_url)

调用示例:

for raceno in range(2, 6):
    opentab(raceno)

这个方案不仅减少了冗余的变量定义,还通过driver.window_handles[-1]直接定位最新窗口,避免了索引计算错误的可能。

内容的提问来源于stack exchange,提问作者jw32001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:45:40