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

如何在Python函数中用字符串变量替代含双引号的字面量字符串?

修改后的Python函数实现

以下是添加参数并动态生成XPATH的完整函数:

def clickButtonViaText(aria_label_text):
    url = 'https://finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL'
    options = Options()
    options.add_argument('--headless')
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    driver.get(url)
    # 动态生成XPATH表达式,将传入的参数替换到aria-label属性值中
    xpath_expr = f'//button[@aria-label="{aria_label_text}"]'
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath_expr))).click()
    time.sleep(10)
    soup = BeautifulSoup(driver.page_source, 'html.parser')

关键修改点:

  • 函数定义新增字符串参数aria_label_text(语义化命名,比str_variable更清晰)
  • 使用Python的f-string格式化语法,将传入的参数动态插入到XPATH表达式中,生成目标按钮的定位路径
  • 保留原函数其他逻辑不变,仅替换硬编码的"Total Assets"为参数变量

调用示例:

# 点击"Total Assets"按钮
clickButtonViaText("Total Assets")
# 点击其他aria-label的按钮,比如"Total Liabilities"
clickButtonViaText("Total Liabilities")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:02:47