Python/selenium - 定位元素 'By' - 用变量指定定位器策略?

标签 python selenium

已经创建了一个 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/

相关文章:

python - 重复 B 列中的值,直到 python 中的 A 列发生变化

python - django 1.8 View 中的循环

python - 使用 Python 进行日志记录。处理程序和控制台副本

javascript - 使用Selenium + Scrapy

python - 使用 selenium 进行网页抓取,单击具有相同/相似名称且输入文本忽略大小写的链接

python - 如何让wx.TextCtrl 多行文本平滑更新?

python - 如何替换 r'\xb 0' with r'\260'

selenium - Zalenium:OpenShift环境中的504网关超时

python-3.x - 使用 Selenium ,如何单击下拉菜单进入https://www.phptravels.net/的登录页面

java - Selenium WebDriver "Click"和 JavascriptExecutor Click 有什么区别