我将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
答案 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')
如果您要按id
,xpath
,css
...进行搜索,只需将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')