Python/selenium - locate elements 'By' - specify locator strategy with variable?
<p>Having created a selenium browser and retrieved a web page, this works fine:</p>

<pre><code>...
if selenium_browser.find_element(By.ID, 'id_name'):
    print "found"
...
</code></pre>

<p>given a tuple like this:</p>

<pre><code>tup = ('ID', 'id_name')
</code></pre>

<p>I'd like to be able to locate elements like this:  </p>

<pre><code>if selenium_browser.find_element(By.tup[0], tup[1]):
</code></pre>

<p>but I get this error</p>

<pre><code>AttributeError: type object 'By' has no attribute 'tup'
</code></pre>

<p>How can I do this without having to write:</p>

<pre><code>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
</code></pre>

<p><a href="http://selenium-python.readthedocs.io/api.html?highlight=#module-selenium.webdriver.common.by" rel="nofollow">http://selenium-python.readthedocs.io/api.html?highlight=#module-selenium.webdriver.common.by</a></p>

<p>If you want to directly provide a tuple to <code>find_element</code>, add a <code>*</code> in front:</p>

<pre><code>locator = (By.ID, 'id')
element = driver.find_element(*locator)
</code></pre>

<p>Or with the method provided as a string:</p>

<pre><code>locator = ('ID', 'id_name')
driver.find_element(getattr(By, locator[0]), locator[1])
</code></pre>

python selenium