Reputation: 77
I'm trying to embed a variable into an xpath expression. This is very straight-forward, but for some reason, it is not working for me.
The following code below works great but I want to make the string Feb
a variable so I can pass through Jan, Mar, etc.
reverse_month_select = browser.find_elements_by_xpath("//div[@class='datepicker-months']/table/tbody/tr/td/span[contains(@class, 'month') and text() = 'Feb']")[0]
For some reason, this code fails as I receive an IndexError:
list index out of range month_select = "Jan"
reverse_month_select = browser.find_elements_by_xpath("//div[@class='datepicker-months']/table/tbody/tr/td/span[contains(@class, 'month') and text() = " + month_select + "]")[0]
Upvotes: 2
Views: 933
Reputation: 24930
I'm still now sure what exactly went wrong, but try feeding the months to the xpath expression using f-strings and let me know if it works:
cal = ['Jan','Feb','March'] #etc.
for month in cal:
expression = f"//div[@class='datepicker-months']/table/tbody/tr/td/span[contains(@class, 'month') and text() = '{month}']"
And then change your definition to:
reverse_month_select = browser.find_elements_by_xpath(expression)[0]
Upvotes: 1