在Python Selenium中使用变量和跟随兄弟的正确语法是什么? [英] What is the correct syntax for using a variable and following-sibling in Python Selenium?
问题描述
我正在使用Python和Selenium Webdriver.
I'm using Python and Selenium Webdriver.
我有以下代码可以正常工作:
I have the following code which works as expected:
driver.find_element_by_xpath('//p[text()="text"]/../following-sibling::td/div/div/table/tbody/tr/td/a[@class ="class_name"]')
我想将上面的文本"更改为一个变量,类似于以下内容:
I would like to change the above "text" to a variable, similar to the below:
driver.find_element_by_xpath('//p[text()="%s"] % variable_name/../following-sibling::td/div/div/table/tbody/tr/td/a[@class ="class_name"]')
这无效,因为它不是有效的XPath表达式.任何人都可以提供正确的编码帮助吗?
This doesn't work as it isn't a valid XPath express. Can anyone help with the correct coding please?
同样,如果有一种方法可以在后继同级中搜索文本,那也将很有用.类似于:
Also, if there is a way to search for text in the follow-sibling that would also be useful. Something similar to:
driver.find_element_by_xpath('//p[text()="%s"] % variable_name/../following-sibling:[div@text()= "text"]')
推荐答案
编写'//p[text()="%s"] % variable_name/../following-sibling::td/div/div/table/tbody/tr/td/a[@class ="class_name"]'
时,创建了一个字符串,其中字面上包含 %s
和% variable_name
. %
运算符和要替换的变量在字符串文字之外:
When you wrote '//p[text()="%s"] % variable_name/../following-sibling::td/div/div/table/tbody/tr/td/a[@class ="class_name"]'
, you created a string that literally contains %s
and % variable_name
. The %
operator and the variable(s) to be substituted go outside of the string literal:
'//p[text()="%s"]/../following-sibling::td/div/div/table/tbody/tr/td/a[@class ="class_name"]' % variable_name
这篇关于在Python Selenium中使用变量和跟随兄弟的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!