XPath: Find element that contains text X and not Y
我正在尝试使用
我已经尝试过这种语法,但是没有使它起作用(请注意寄生):
1 | choco = driver.find_element_by_xpath("//*[text()[contains(., 'Chocolate')] and not[[contains(., 'Dark')]]]") |
以下是使用换行符和串联的相同代码,以提高可读性:
1 2 3 4 | choco = driver.find_element_by_xpath(( "//*[text()[contains(., 'Chocolate')]" + "and not[[contains(., 'Dark')]]]" )) |
请尝试按照
1 | //*[contains(text(),"Chocolate")][not(contains(text(),"Dark"))] |
这里是仅使用一组方括号的语法。
对于包含单词'Chocolate \\'但不包含\\'Dark \\'的元素,请使用:
1 | //*[contains(text(), 'Chocolate') and not(contains(text(), 'Dark'))] |
对于元素的文本,请使用:
1 | //text()[contains(., 'Chocolate') and not(contains(., 'Dark'))] |
给出以下XML:
1 2 3 4 | <doc> <e>Dark Chocolate</e> <e>Chocolate</e> </doc> |
第一个表达式的结果为:
1 2 | > xpath -e"//*[contains(text(), 'Chocolate') and not(contains(text(), 'Dark'))]" test.xml <e>Chocolate</e> |
第二个表达式的结果为:
1 2 | > xpath -e"//text()[contains(., 'Chocolate') and not(contains(., 'Dark'))]" test.xml Chocolate |