简体   繁体   中英

Finding web element using javascript statments through Python Selenium WebDriver

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM