已经创建了一个 selenium 浏览器并检索了一个网页,这工作正常:
...
if selenium_browser.find_element(By.ID, 'id_name'):
print "found"
...
给定一个这样的元组:
tup = ('ID', 'id_name')
我希望能够定位这样的元素:
if selenium_browser.find_element(By.tup[0], tup[1]):
但是我得到了这个错误
AttributeError: type object 'By' has no attribute 'tup'
我怎样才能做到这一点而不必写:
if tup[0] == 'ID':
selenium_browser.find_element(By.ID, tup[1])
...
elif tup[0] == 'CLASS_NAME':
selenium_browser.find_element(By.CLASS_NAME, tup[1])
...
elif tup[0] == 'LINK_TEXT':
etc etc
http://selenium-python.readthedocs.io/api.html?highlight=#module-selenium.webdriver.common.by
最佳答案
如果想直接给find_element
提供元组,在前面加一个*
:
locator = (By.ID, 'id')
element = driver.find_element(*locator)
或者使用作为字符串提供的方法:
locator = ('ID', 'id_name')
driver.find_element(getattr(By, locator[0]), locator[1])
关于Python/selenium - 定位元素 'By' - 用变量指定定位器策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39981228/