Python中driver.find_element_by_xpath引用列表元素时索引失效的正确写法咨询
Let's break down what's going wrong and how to fix it:
1. The Root Cause: String Escaping & XPath Syntax Missteps
Your original code has two key issues:
- You’re using HTML entity escapes (
") in a Python string, which Python doesn’t interpret correctly. This leads to your XPath query being parsed incorrectly, so the(list1)[x]part isn’t matching as you expect. - The mixed quoting (single quotes + unescaped
") confuses Python about the boundaries of yourcontains()argument, making the condition match a partial string instead of the exact(list1)[x]pattern.
2. Correct Code for Static Index
First, fix the string escaping to properly define your XPath. Here are two valid, clean ways:
Option A: Use double quotes for the XPath string
driver.find_element_by_xpath("//*[starts-with(@href, 'javascript') and contains(@href, '(list1)[3]')]")
Option B: Escape single quotes inside a single-quoted string
driver.find_element_by_xpath('//*[starts-with(@href, \'javascript\') and contains(@href, \'(list1)[3]\')]')
Both versions will correctly target elements where the href starts with javascript and contains the exact string (list1)[3].
3. Dynamic Index (Replace 3 with any number)
If you want to use a variable for the index (e.g., swap 3 with a value from your code), use an f-string for straightforward formatting:
target_index = 5 # Replace with your desired index driver.find_element_by_xpath(f"//*[starts-with(@href, 'javascript') and contains(@href, '(list1)[{target_index}]')]")
Why Your Original Code Failed
The " entities are designed for HTML, not Python strings. When Python parsed your original code, it didn’t recognize those as quote marks—so the contains() condition wasn’t matching the exact (list1)[x] string you intended. Instead, it was matching a partial substring that happened to exist in the first element, which is why you always ended up with the index 0 result.
内容的提问来源于stack exchange,提问作者Aeternus

