Hush
Hush

Reputation: 44

How to insert variable to x_path?

My code that doesn't work

size_id = "'739'"

path = '"//div[@data-option-value-id=' + size_id + ']"'

driver.find_element_by_xpath(path).click()

working code:

driver.find_element_by_xpath("//div[@data-option-value-id='739']").click()

realy don't know how to fix. I use variauble because it requires different values.

Upvotes: 0

Views: 70

Answers (2)

Trapli
Trapli

Reputation: 1597

In case you are python 3.x, f-strings are your best friends:

path = f'//div[@data-option-value-id="{size_id}"]'
driver.find_element_by_xpath(path).click()

Your mistake was that you didn't enclose the size_id into ".

path = '//div[@data-option-value-id="' + size_id + '"]' could work too.

Upvotes: 1

KunduK
KunduK

Reputation: 33384

You were close just confuse the quotation.Try below code.

size_id = "739"
path = "//div[@data-option-value-id='" + size_id + "']"

driver.find_element_by_xpath(path).click()

Or you can use format function which is much easier.

size_id = "739"
driver.find_element_by_xpath("//div[@data-option-value-id='{}']".format(size_id)).click()

Upvotes: 1

Related Questions