我正在努力让 Selenium 遍历大量替代条件 XPath,寻找满足以下条件的元素:可能匹配– 并将其传递给对象elmnt
.
目前,使用OR
操作员 (|
),代码很快就会变得非常重复和详尽,尤其是当存在很多可能的变化时。
在下面的示例中,唯一的变化是我开始寻找h1
, h2
, or h3
。其余的都是一样的。
for word in ["testString1", "testString2", "testString3"]:
try:
elmnt = driver.find_element_by_xpath(
(
"//h1[text()[contains(., '%s')]]" % word +
"/following::p" +
"|" +
"//h1[text()[contains(., '%s')]]" % word +
"/following::span" +
"|" +
"//h2[text()[contains(., '%s')]]" % word +
"/following::p" +
"|" +
"//h2[text()[contains(., '%s')]]" % word +
"/following::span" +
"|" +
"//h3[text()[contains(., '%s')]]" % word +
"/following::p" +
"|" +
"//h3[text()[contains(., '%s')]]" % word +
"/following::span"
)
).text
except:
pass
else:
print elmnt
break
但在我的实际代码中,我将考虑更多的变化,包括各种节点类型/following::
除了p
and span
.
问题:有什么方法可以简化(缩短)这个吗?
我的第一个希望是可以做类似的事情:
"//[h1|h2|h3][text()[contains(., '%s')]]" % word
即or
运算符可以“融入”XPath 表达式中,而不必像示例中那样使用完全详尽的字符串连接。如果是这样,这个想法就可以全面应用。
然而,这似乎不可能。
解决方案是创建某种生成函数来创建整个 xPath 字符串,还是其他方法?