简体   繁体   中英

How to implement more than one variable string into xpath as %s can only support one variable in the xpath only?

I am writing a python code finding element between 'SECTION A' and 'SECTION B' using xpath:

driver.find_elements("xpath", "//*[preceding-sibling::div[contains(@class,'titleWrap') and .//div[contains(@data-section-name,'SECTION A')]] and following-sibling::div[contains(@class,'titleWrap') and .//div[contains(@data-section-name,'SECTION B')]]]//span[normalize-space(text()) and contains(@class,'label')] ")

but I want to do the same thing for between SECTION and B SECTION C and so on, so I want to implement a function to pass the first section and the second section, but how modify the code such that it can pass two variables to the xpath? I know I can use %s but it can only support one variable only?

driver.find_elements("xpath", "//*[preceding-sibling::div[contains(@class,'titleWrap') and .//div[contains(@data-section-name,'%s')]] and following-sibling::div[contains(@class,'titleWrap') and .//div[contains(@data-section-name,'SECTION B')]]]//span[normalize-space(text()) and contains(@class,'label')] "%firstsection) #How about secondsection for 'SECTION B'?

You can format a string with multiple variables.
There are several ways to do that in Python. For example this:

xpath_template = "//*[preceding-sibling::div[contains(@class,'titleWrap') and .//div[contains(@data-section-name,'{0}')]] and following-sibling::div[contains(@class,'titleWrap') and .//div[contains(@data-section-name,'{1}')]]]//span[normalize-space(text()) and contains(@class,'label')]"
xpath_expression = xpath_template.format("SECTION B", "SECTION C")
driver.find_elements(By.XPATH, xpath_expression)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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