Manipulate xpath using variables

2019-03-01 08:07发布

So I have the code where the user inputs a color variable and the string for it is called color. Example link - https://www.supremenewyork.com/shop/jackets/k56l3oteu/hjylineo1 . So next I try to find it on the website using

driver.find_element_by_xpath("//a[@data-style-name='{}'".format(color.get()))

The syntax is wrong and I am not sure how to find it correctly using the variable that users entered before. Also the question, when one of those colors was located how to choose that color as the checkout option, not sure if I explained it right. Thanks for any information

2条回答
Melony?
2楼-- · 2019-03-01 08:33

Try using the following CSS selector to identify the element:

'p.style.protect'

It looks like that will uniquely identify the element that shows what color is chosen.

Then your color is stored in the inner HTML of the element, so you can grab that with something like

chosenColor = 
driver.find_element_by_css_selector('p.style.protect').text()

OK, I understand now that you want to use xPath to dynamically select an element based on the color. I noticed that the xPath

'//*[@id="details"]/ul/li[4]/a[1]'

find the top-right element,

'//*[@id="details"]/ul/li[4]/a[2]'

finds the middle-right element and so on...

Thus if you can simply use a map to map colors to the numbers, something like

colorMap = {
    "brown" : 1,
    "cyan" : 2,
    "grey" : 3,
    ...
}

(not sure if the colors match up correctly in my example but hope you get the idea)

Then,

driver.find_element_by_xpath('//*[@id="details"]/ul/li[4]/a[' + 
'colorMap.("<whatever color you are looking to select>")' + ]').click()

should select the element with the color you specified.

Is that helpful? Let me know if you have any questions.

查看更多
SAY GOODBYE
3楼-- · 2019-03-01 08:36

You can use string formats below, but there is error in your xpath - missing ] at the end:

driver.find_element_by_xpath("//a[@data-style-name='{}']".format(color.get()))
driver.find_element_by_xpath("//a[@data-style-name='{0}']".format(color.get()))
driver.find_element_by_xpath("//a[@data-style-name='%s']" % color.get())
查看更多
登录 后发表回答