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

Selenium入门:XPath中大括号使用引发语法错误的解决咨询

Hey there! Let's fix that syntax error you're hitting. The problem boils down to two issues in your code: conflicting quote marks and Python trying to interpret curly braces as string formatting placeholders.

First, you wrapped your XPath in double quotes, but the data-eui-handler attribute value also uses double quotes — this makes Python think your string ends early, triggering a syntax error. Second, those { ... } blocks in the attribute value look like Python's string formatting syntax (like how f"Hello {name}" works), so Python tries to parse them even if you don't intend that.

Solution 1: Use Raw Triple-Quoted Strings (Cleanest Option)

Triple quotes (""" or ''') let you include both single and double quotes inside your string without escaping them. Adding the r prefix creates a raw string, which tells Python not to interpret curly braces as formatting placeholders or escape characters like \.

Here's how your code would look (I swapped inner double quotes to single quotes for extra readability):

ref_code = driver.find_elements_by_xpath(r"""//tr[@data-eui-handler="{ event:'click',handler: 'eui.app.controller.search_results.selectRow' }"]/td[1]""")

You could even leave the inner double quotes intact — triple quotes handle either without issues.

Solution 2: Escape Quotes and Use a Raw String

If you prefer not to use triple quotes, you can escape the double quotes inside your XPath with backslashes, and still use the r prefix to avoid formatting conflicts:

ref_code = driver.find_elements_by_xpath(r"//tr[@data-eui-handler=\"{ event:\"click\",handler: \"eui.app.controller.search_results.selectRow\" }\"]/td[1]")

This works, but it's harder to read compared to the triple-quote method.

Solution 3: Switch Quote Types in the XPath

XPath allows using single quotes for attribute values, so you can rewrite the data-eui-handler part to use single quotes instead of double quotes. Wrap the entire XPath in double quotes (with the r prefix) to avoid conflicts:

ref_code = driver.find_elements_by_xpath(r"//tr[@data-eui-handler='{ event:\"click\",handler: \"eui.app.controller.search_results.selectRow\" }']/td[1]")

Again, the r prefix is critical here to stop Python from messing with the curly braces.

Any of these methods will resolve your syntax error. The triple-quoted raw string is the easiest to read and maintain, especially for longer XPath expressions like this.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:52:39