在Python Selenium中的xpath中使用变量

在Python Selenium中的xpath中使用变量

问题描述:

我一直在弄清楚如何获取变量以使用Selenium时遇到了麻烦.这篇文章似乎有所帮助(变量无法在括号内使用),但我仍然可以使其无法正常工作.

I've been having trouble figuring out how to get a variable to work Selenium. This post seems to have helped (Variable not working inside parenthesis) but I still can't get it to work.

当我使用实际值时,它起作用.在这种情况下,阿拉巴马州.我创建了一个名为state的变量,以便我可以调用 在我的职能.我有13个州要经历.

When I used the actual value it works. In this case AL-Alabama. I created a variable called state so that I can just call that in my function. I have 13 states to run through.

driver.find_element_by_xpath("//option[@value='AL-Alabama']").click()

此变量使用状态变量,并在查看错误消息时将变量值显示为AL-Alabama.所以看起来 它引用了网页中的正确值.不知道我缺少什么或为什么它不起作用.任何指导将不胜感激.

This one uses the state variable and in looking at error message it shows the variable value as AL-Alabama. So it seems like it's referencing the correct value in the web page. Not sure what I'm missing or why it's not working. Any guidance would be appreciated.

driver.find_element_by_xpath('//option[@value=' + state + ']').click()
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//option[@value=AL-Alabama]"}

该值的编码方式中不包含该值的单引号.试试:

The single quotes around the value are not present with how you coded it. Try:

driver.find_element_by_xpath("//option[@value='" + state + "']").click()