-1

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"]')

This doesn't work as it isn't a valid XPath express. Can anyone help with the correct coding please?

Edit: 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"]')
Pavel_K
  • 10,748
  • 13
  • 73
  • 186
blountdj
  • 599
  • 1
  • 11
  • 23
  • Possible duplicate of [Putting a variable inside a string (python)](https://stackoverflow.com/questions/2960772/putting-a-variable-inside-a-string-python) – JeffC Aug 16 '17 at 01:22

1 Answers1

2

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
jasonharper
  • 9,450
  • 2
  • 18
  • 42