Python EXEC显示错误:名称未定义

时间:2018-09-03 08:38:24

标签: python selenium exec

我将exec与硒一起使用,如下所示

from selenium import webdriver
search_method = 'find_element_by_class_name'
search_word = 'keyword'
exec("elem_search_word = driver." + search_method + "('" + search_word + "')")
elem_search_word.send_keys('python'))

但是我遇到错误,该怎么办?

elem_search_word.send_keys(str(args.search))
NameError: name 'elem_search_word' is not defined

1 个答案:

答案 0 :(得分:1)

我无法重现您的问题,但是恕我直言,在这种情况下,您应避免使用exec()。请尝试以下操作:

search_method = 'class name'
search_word = 'keyword'
elem_search_word = driver.find_element(search_method, search_word)
elem_search_word.send_keys('python')

如果您要按idxpathcss ...进行搜索,只需将search_method设置为适当的值

或者:

from selenium.webdriver.common.by import By

search_method = By.CLASS_NAME
search_word = 'keyword'
elem_search_word = driver.find_element(search_method, search_word)
elem_search_word.send_keys('python')