Finding web element using javascript statments through Python Selenium WebDriver

Viewed 177

I want to find specific web element by executing javascript code and then click on that element. This is my code:

driver.get('https://justjoin.it')
driver.maximize_window()


for position in [x.text for x in driver.find_elements_by_xpath('//div[@class="css-1x9zltl"]')]:
      javascript = f"document.evaluate('//div[contains(@class, 'css-1x9zltl') and text()='{position}']', document);"
      driver.execute_script(javascript).click()

And when I run this code console throws me this error:

selenium.common.exceptions.JavascriptException: Message: javascript error: missing ) after argument list

Any ideas how to solve this?

1 Answers

It probably has to do with the interaction of the single and double quote marks within your f-string. Try escaping one by changing your javascript to:

javascript = f"document.evaluate(\"//div[contains(@class, 'css-1x9zltl') and text()='{position}']\", document);"

and see if it works.

Related