如何缩短包含多个OR条件的长XPath表达式?

3
我正在努力让Selenium通过大量的备选条件XPath搜索元素,寻找可能匹配的元素,并将其传递给对象“elmnt”。
目前,使用“OR”运算符(“|”),当可能的变体很多时,代码会变得非常重复和详尽。
在下面的示例中,唯一的变化是我开始查找“h1”,“h2”或“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::中除pspan以外的各种节点类型。

问题:有没有简化(缩短)这个的方法?

我最初的希望是能够做到类似以下的方式:

"//[h1|h2|h3][text()[contains(., '%s')]]" % word

or运算符可以“烘进”XPath表达式中,而不必像示例中那样使用完全耗尽的字符串连接。如果是这样,这个想法本来可以应用到所有情况中。但是似乎并不可行。解决方案是创建某种生成函数以创建整个xPath字符串,还是其他方法?

2
不确定是否重复,但这至少可以部分回答:https://dev59.com/03RB5IYBdhLWcg3wF0DH - alecxe
网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接