Dustin Knight Dustin Knight - 1 year ago 399
Python Question

Making flexible XPath for Selenium (Python)

I am trying to use selenium and python to set the text contents of a web element to a string.

The code:

monthname = browser.find_element_by_xpath("//*[@id='monthRow-7']/td[1]").text
works but I want to be able to change
to include a different number.

My idea is to ask the user for a month (1-12) and what they enter is stored into a string called monthnum. Then I can concatenate the string monthnum into the xpath to change the number of monthRow. Ex. user enters 9 when prompted for the month number so monthRow-7 is changed to monthRow-9.

I have tried:
monthname = browser.find_element_by_xpath(("\"//*[@id='monthRow-") + monthnum + ("']/td[1]\"")).text
is a string set by user input.

but that gives me an error that says:

"Message: invalid selector: Unable to locate an element with the xpath expression "//*[@id='monthRow-7']/td[1]" because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type."

The xpath expression listed in the error is the same xpath expression I had in my code that actually works though. Is there any way where I can change the xpath by assigning bits of it to variables?

Answer Source

I'd use string formatting for this.

monthnum = 7
monthname = browser.find_element_by_xpath("//*[@id='monthRow-{}']/td[1]".format(monthnum)).text

Here {} will be replaced by the value of monthnum.

I'm not quite sure what you were trying, but I think your solution should work like this:

monthname = browser.find_element_by_xpath("//*[@id='monthRow-" + monthnum + "']/td[1]").text

All those round brackets and extra quotes should be unnecessary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download