使用变量操作 xpath [英] Manipulate xpath using variables

查看:32
本文介绍了使用变量操作 xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有用户输入颜色变量的代码,它的字符串称为颜色.示例链接 - https://www.supremenewyork.com/shop/jackets/k56l3oteu/hjylineo1 .所以接下来我尝试使用

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

推荐答案

尝试使用以下 CSS 选择器来标识元素:

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.

然后你的颜色存储在元素的内部 HTML 中,所以你可以用类似的东西来获取它

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()

<小时>

好的,我现在明白您想使用 xPath 根据颜色动态选择元素.我注意到 xPath


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]'

找到右上角的元素,

'//*[@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)

那么,

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.

这篇关于使用变量操作 xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆