繁体   English   中英

如何使用%s在python中为Selenium构造带有变量的xpath表达式

[英]How to construct a xpath expression with variable for Selenium in python using %s

我正在尝试使用硒根据调用时传递给函数的变量来定位和选择某个元素。 我以为,有了一个好的ol,这将足够简单:

show = browser.find_element_by_xpath("//*[contains(text(), '%s')]" % eventName)

但是,我收到错误消息:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //*[contains(text(), 'VARIABLE_TEXT')] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(text(), 'VARIABLE_TEXT')]' is not a valid XPath expression.

这是我试图选择的HTML的一部分-提炼和简化了:

<ul>
<li class="seriesElement">
<input id="productionId_0" name="productionIds" type="checkbox" value="VALUE"><input type="hidden" name="_productionIds" value="on"><label for="productionId_0" class="prodColor0">TEXT</label>
</li>
<li class="seriesElement">
<input id="productionId_1" name="productionIds" type="checkbox" value="VALUE"><input type="hidden" name="_productionIds" value="on"><label for="productionId_1" class="prodColor1">TEXT</label>
</li>
</ul>

这些列表元素很多,我想按文本选择一个。 我是否对xpath表达式使用了错误的语法,或者这完全是另一种野兽?

您可以尝试这种方式。看看是否有帮助。

VAR_TEXT="TEXT"
print(driver.find_element_by_xpath("//label[contains(text() ,'" + VAR_TEXT + "')]").text)

要么

VAR_TEXT="TEXT"
print(driver.find_element_by_xpath("//*[contains(text() ,'" + VAR_TEXT + "')]").text)

要么

VAR_TEXT="TEXT"
print(driver.find_element_by_xpath("//label[text()[contains(.,'" + VAR_TEXT + "')]]").text)

要么

VAR_TEXT="TEXT"
print(driver.find_element_by_xpath("//*[text()[contains(.,'" + VAR_TEXT + "')]]").text)

要基于可变文本定位某个元素,可以编写如下方法:

  • 使用.

     def find_myelement_with_text(myString): show = browser.find_element_by_xpath("//label[.='" + myString + "']") 
  • 使用%s

     def find_myelement_with_text(myString): show = browser.find_element_by_xpath("//label[contains(text(), '%s')]" % (myString)) 
  • 使用format()

     def find_myelement_with_text(myString): show = browser.find_element_by_xpath('//label[contains(text(), "{}")]'.format(myString)) 

现在,您可以在程序中的任何位置调用此方法,如下所示:

find_myelement_with_text("TEXT")

好的%s工作-您可以在错误消息中看到替换,问题出在xpath本身。
如果通过独立的解析器(而不是浏览器的解析器)运行它,则会看到错误的元凶:

无法执行XPath操作。 包含一个以上项目的序列不允许作为contains()(“”,“”,...)的第一个参数

(这是Java语言,其他语言则类似)

长话短说,困扰它的是text()的输出-它是一个节点集; 如果您将该功能更改为. ,它应该可以工作:

show = browser.find_element_by_xpath("//*[contains(., '%s')]" % eventName)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM