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):

AJ Goudel
  • 339
  • 5
  • 14
  • 2
    use [f-string](https://peps.python.org/pep-0498/): `f'//button[@aria-label={str_variable}]'` – It_is_Chris Mar 01 '23 at 20:49
  • There are several ways of how to achieve this. Have a look at string formatting – ThiloOS Mar 01 '23 at 20:51
  • @ShadowRanger what do you mean? `def clickButtonViaText(str_variable='"Total Assests"'): print(f'//button[@aria-label={str_variable}]')` – It_is_Chris Mar 01 '23 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](/q/32874539/4518341). 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()`](https://docs.python.org/3/library/xml.sax.utils.html#xml.sax.saxutils.quoteattr). – wjandrea Mar 01 '23 at 21:08

1 Answers1

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()
    ...
wjandrea
  • 28,235
  • 9
  • 60
  • 81
sahasrara62
  • 10,069
  • 3
  • 29
  • 44