Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
执行存储在变量(Python>;Webdriver)中的Selenium命令_Python_Selenium_Selenium Webdriver_Webdriver - Fatal编程技术网

执行存储在变量(Python>;Webdriver)中的Selenium命令

执行存储在变量(Python>;Webdriver)中的Selenium命令,python,selenium,selenium-webdriver,webdriver,Python,Selenium,Selenium Webdriver,Webdriver,我正在尝试创建一个定义,允许我单击一个对象,而不考虑元素类型。为了实现这一点,我创建了一个包含要运行的命令的变量 def clickOnStaleElement(driver, objStrategy, element): lhs, rhs = objStrategy.split(".", 1) myCommand = "driver.find_element_by_"+rhs.lower()+"(\""+element+"\").click()" 我似乎不知道如何执行这个存储

我正在尝试创建一个定义,允许我单击一个对象,而不考虑元素类型。为了实现这一点,我创建了一个包含要运行的命令的变量

def clickOnStaleElement(driver, objStrategy, element):
    lhs, rhs = objStrategy.split(".", 1)
    myCommand = "driver.find_element_by_"+rhs.lower()+"(\""+element+"\").click()"
我似乎不知道如何执行这个存储在变量中的命令。我尝试了“驱动程序。执行脚本()”,但收到了WebDriverException。尝试“exec()”、&“eval()”导致文本挂起。我如何做到这一点?有没有更好的方法来实现这种行为?我意识到我试图实现这种行为的方式可能并不理想,所以我愿意用更好的方式来完成同样的任务。如果可能的话,我不希望为每种元素类型创建“if/then”语句

def clickOnStaleElement(driver, objStrategy, element):
    lhs, rhs = objStrategy.split(".",1) #ASSUMING only valid stuff comes down like "???.xpath" , "???.name" "???.id" bla bla ... we'll just keep this here for now....
    if rhs == 'xpath':
        myCommand = driver.find_eleemnt_by_xpath(element) # xpath example, you better hope you entered valid xpath as "element"
    elif rhs == 'id':
        myCommand = driver.find_eleemnt_by_id(element)
    elif rhs == 'name':
       #you get the idea
.
.
.
    else:
        print("rhs, not recognized/valid/watever")
    myCommand.click()
如果watever
rhs
上的语句是,我会将其分解为每个都有自己的If语句


同样在我看来,没有理由将“?”之类的内容传递到objStrategy中,为什么不直接传递您真正想要的内容呢?

您可以创建一个字典,提供从字符串到函数的映射,然后执行简单的查找:

strategy = {
    "id":   driver.find_element_by_id,
    "name": driver.find_element_by_name,
    ...
}
find_element = strategy.get(rhs.lower())
find_element(element).click()

您可能希望有一个默认方法,或者为
rhs.lower()
与字典中的任何内容都不匹配的情况做准备。

您不希望这样做。它形成了一个坏习惯,使得代码本身很难看/理解。加上
exec
eval
几乎是这里的诅咒词,哈哈。够公平了,@TehTris。这就是为什么我问了第二个问题,关于实现这一目标的更好方法。除了为每种可能的元素类型创建if/then语句之外,我更喜欢做其他事情。谢谢你的回复!这是光滑的。这个答案值得挑选。谢谢@Bryan Oakley。这看起来肯定比我的好。好吧,如果分离它们是我最好的选择,我不应该删除split命令并改为这样做吗<代码>如果objStrategy==“By.LINK\u TEXT”:
驱动程序。通过链接文本(element)查找元素。单击()
elif objStrategy==“By.XPATH”:
驱动程序。通过链接文本(element)查找元素。单击()
否则:
引发NoTouchElementException(“错误”)