0

I have a function in Python:

def clickButtonViaText():
    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)
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[@aria-label="Total Assets"]'))).click()
    time.sleep(10)
    soup = BeautifulSoup(driver.page_source, 'html.parser')

I want to add an argument to my function that takes a string and I want to pass the string in //button[@aria-label="Total Assets"] as something like //button[@aria-label=str_variable] where str_variable is an argument passed with the function. Example: def clickButtonViaText(str_variable):

4
  • 2
    use f-string: f'//button[@aria-label={str_variable}]' Commented Mar 1, 2023 at 20:49
  • There are several ways of how to achieve this. Have a look at string formatting Commented Mar 1, 2023 at 20:51
  • @ShadowRanger what do you mean? def clickButtonViaText(str_variable='"Total Assests"'): print(f'//button[@aria-label={str_variable}]') Commented Mar 1, 2023 at 20:56
  • I closed this as a duplicate, but now I'm realizing the quotes might make it more tricky. I'm not very familiar with this area myself so I'm not sure, but here's an existing question that might be more precise: Using a variable in xpath in Python Selenium. And if str_variable might contain quote characters itself, there's probably some library with a quote() or escape() method that could handle it, possibly xml.sax.saxutils.quoteattr(). Commented Mar 1, 2023 at 21:08

1 Answer 1

3

with f-string you can get this as

def clickButtonViaText(str_variable):
    ...
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, f'//button[@aria-label="{str_variable}"]'))).click()
    ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.