如何使用%s在python中使用Selenium变量构建xpath表达式 - python

我正在尝试使用硒根据调用时传递给函数的变量来定位和选择某个元素。我以为,有了一个好的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)

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何在python中将从PDF提取的文本格式化为json - python

我已经使用pyPDF2提取了一些文本格式的发票PDF。我想将此文本文件转换为仅包含重要关键字和令牌的json文件。输出应该是这样的:#PurchaseOrder {"doctype":"PO", "orderingcompany":"Demo Company", "su…

查找字符串中的行数 - python

我正在创建一个python电影播放器​​/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …

Python中的Json操作 - python

Latest_json和Historic_json函数返回:return(frame.to_json(orient='records')) 主功能:recentdata = recent_json(station) historicdata = historic_json(station) alldata = historicdata +…