bluescreenofdeath2016 bluescreenofdeath2016 - 1 month ago 8
Python Question

How do I workaround the element not visible exception while using Selenium for Python

I'm using Selenium to click a button on a website. The button is choosing a state. When the drop-down. The elements are not initially visible. You need to click on the "select" button and then a drop down appears.

The select element looks like this.

<select name="state" style="display: none;">
<option value="0">select</option>
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>


I've tried it using:

driver.find_element_by_xpath("/html/body/div[1]/div[3]/form/div/div[9]/div[2]/div/div/div[1]").click()
driver.find_element_by_xpath(state_xpath).click()


The first statement clicks the select buttons so that options appear. The second statement chooses the option by clicking on it. This works fine for the first few options but when I need to choose an option that isn't visible it returns the ElementNotVisibleException

When I try to find it using the select class. It again returns ElementNotVisible. This may be because the display is set to none for this element so the code below doesn't work either.

select = Select(driver.find_element_by_name('state'))
select.select_by_value('2')


How do I work around this. Is there any way to scroll down the options so that more of them become visible.

Answer

For anyone stuck on the same problem. The issue here is that the element is not visible. Since I was unable to solve it using driver.execute_script. I found a solution by making the mouse click on the scroll bar so as to scroll it down (By pressing just below the bar itself so that it moves down). I first added a function click that clicks on an x and y position. And ran it whenever I needed a certain element to be visible.

You can easily find x and y location by using a freeware software to do the job.

import win32api, win32con
def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)