Hidden element blocking me from clicking on button

老子叫甜甜 提交于 2020-08-10 19:16:31

问题


The following code does the following:

  1. Accesses a URL with the FIRST date
  2. Closes the "Understanding origins" pop-up window by clicking on SKIP
  3. Click on the "Download data" button
  4. Opens a new tab with the NEXT date
  5. closes previous tab (FIRST date URL)
  6. TRIES to click on "Download data" again

The problem I have is on number 6. It gives me the "element click intercepted" error, and I assume it's because it thinks a NEW "Understanding origins" pop-up window appeared.

However, no pop-up window appears this time, unlike the first time I opened the browser (FIRST date URL). I even tried using the same code to click on the SKIP button this time, but it still gives me the same error.

How can I get around this and be able to click on the "Download data" button every time I open a new tab? Note: I'm opening thousands of tabs, one at a time here.

My code:

# Load Chrome driver and movement.uber.com/cities website
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)

# Attributing the city name and the center-most zone code (or origin) to variables so they can be inserted in the URL later
city = 'atlanta' # Note: Atlanta might be missing data from 10/25/2018 - 10/29/2018
origin_code = '1074'
coordinates = '&lat.=33.7489&lng.=-84.4234622&z.=12'

# Open URL for the first day in the desired city (change coordinates depending on city)
driver.get('https://movement.uber.com/explore/' + city + '/travel-times/query?si' + origin_code + '&ti=&ag=taz&dt[tpb]=ALL_DAY&dt[wd;]=1,2,3,4,5,6,7&dt[dr][sd]=' + 
           '2016-01-02' + '&dt[dr][ed]=' + '2016-01-02' + '&cd=&sa;=&sdn=' + coordinates + '&lang=en-US')

# Agree to privacy preferences
priv_pref_buton = driver.find_element_by_id('privacy_pref_optin')
priv_pref_buton.click()
        
# Skip button only shows up the first time you open the Chrome browser
time.sleep(6)
skip_button = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[3]/div/div[2]/div/div[2]/div/div[1]/button')
skip_button.click()

                                    
# Choosing correct data parameters (Traffix Analysis Zone) and opening date bar in preparation for the calendar loop
# Zone type dropdown only shows up the first time you open the Chrome browser
zone_type_dropdown = WebDriverWait(driver, 8).until(
    EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[1]/div[3]/div/div[2]/div/div/div/div/div[1]/div[2]/div')))
zone_type_dropdown.click()

traffic_analysis_zones = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div/div/ul/li[2]')))
traffic_analysis_zones.click()
        

# Buttons for downloading the dataset
download_button = driver.find_element_by_css_selector('div.f5 button') # //button[contains(@data-baseweb, "button")]')
download_button.click()
time.sleep(3)

# travel_times_download = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[3]/div/div[2]/div/div[1]/div/button[1]')
# travel_times_download.click()


# Day list and loop Solution proposed in StackOverflow
# Generating the correct URLs for each date
def getURL():
    date = datetime(2016,1,3)
    while date <= datetime(2020,3,31):
        yield ('https://movement.uber.com/explore/' + city + '/travel-times/query?si' + origin_code + '&ti=&ag=taz&dt[tpb]=ALL_DAY&dt[wd;]=1,2,3,4,5,6,7&dt[dr][sd]=' +
               date.strftime('%Y-%m-%d') + '&dt[dr][ed]=' + date.strftime('%Y-%m-%d') + '&cd=&sa;=&sdn=&lat.=33.7489&lng.=-84.4234622&z.=12&lang=en-US')
        date += timedelta(days=1)

# Perform iteration through URLs downloading the datasets for each URL
i = 0
print("urls: %i", len(list(getURL())))
for url in getURL():
    i += 1
    if i < 4:
        driver.execute_script("window.open('"+url+"', '_blank')")
        print(url)
        time.sleep(3)
        
        # Create function
        # Agree to privacy preferences
        try:
            priv_pref_buton = driver.find_element_by_id('privacy_pref_optin')
            priv_pref_buton.click()
        
        except:
            pass
        
        # Skip button only shows up the first time you open the Chrome browser
        try:
            time.sleep(6)
            skip_button = driver.find_element_by_css_selector('button.btn btn--link')
        
            skip_button.click()
            
        except:
            pass
        
        time.sleep(3)
        download_button = driver.find_element_by_css_selector('div.f5 button') # //button[contains(@data-baseweb, "button")]')
        download_button.click()
        time.sleep(1)
        
        # travel_times_download = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[3]/div/div[2]/div/div[1]/div/button[1]')
        # travel_times_download.click()
        
        # Switch to previous tab and close it (leaving us with the newly above opened tab)
        tabs = driver.window_handles
        
        if len(tabs) > 1:
            driver.switch_to.window(tabs[0])
            driver.close()
            driver.switch_to.window(tabs[1])

The error is the following:

ElementClickInterceptedException          Traceback (most recent call last)
<ipython-input-89-80ae8e1decd5> in <module>
     70         time.sleep(3)
     71         download_button = driver.find_element_by_css_selector('div.f5 button') # //button[contains(@data-baseweb, "button")]')
---> 72         download_button.click()
     73         time.sleep(1)
     74 

c:\users\i539797\appdata\local\programs\python\python38-32\lib\site-packages\selenium\webdriver\remote\webelement.py in click(self)
     78     def click(self):
     79         """Clicks the element."""
---> 80         self._execute(Command.CLICK_ELEMENT)
     81 
     82     def submit(self):

c:\users\i539797\appdata\local\programs\python\python38-32\lib\site-packages\selenium\webdriver\remote\webelement.py in _execute(self, command, params)
    631             params = {}
    632         params['id'] = self._id
--> 633         return self._parent.execute(command, params)
    634 
    635     def find_element(self, by=By.ID, value=None):

c:\users\i539797\appdata\local\programs\python\python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params)
    319         response = self.command_executor.execute(driver_command, params)
    320         if response:
--> 321             self.error_handler.check_response(response)
    322             response['value'] = self._unwrap_value(
    323                 response.get('value', None))

c:\users\i539797\appdata\local\programs\python\python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response)
    240                 alert_text = value['alert'].get('text')
    241             raise exception_class(message, screen, stacktrace, alert_text)
--> 242         raise exception_class(message, screen, stacktrace)
    243 
    244     def _value_or_default(self, obj, key, default):

ElementClickInterceptedException: Message: element click intercepted: Element <button data-baseweb="button" class="by f6 ae ah f7 f8 f9 fa fb fc fd fe ff dj fg fh cx cy c6 fi fj fk bo bn bp bm b3 cb ck c0 fl fm fn fo fp fq fr fs ft fu fv fw fx fy f5 cd fz g0 g1">...</button> is not clickable at point (212, 634). Other element would receive the click: <div>...</div>
  (Session info: chrome=84.0.4147.105)

回答1:


The problem was that your driver is still focussed on tab one. When you open a new tab you need to change the driver to focus to it.

The intercepted click was caused by download popup on the previous tab.

Option 1 Change this:

driver.execute_script("window.open('"+url+"', '_blank')")

To this:

driver.execute_script("window.open('"+url+"', '_blank')")
driver.switch_to_window(driver.window_handles[1])

Option 2 Alternatively, don't use tabs. Changing the execute_script to this use a singe tab works:

driver.execute_script("window.open('"+url+"', '_self')")

And actually the same as: (which also works)

driver.get(url)

finally, if using a single tab you won't need this:

  # Switch to previous tab and close it (leaving us with the newly above opened tab)
        tabs = driver.window_handles
        
        if len(tabs) > 1:
            driver.switch_to.window(tabs[0])
            driver.close()
            driver.switch_to.window(tabs[1])

however - since tabs will now always be 1, this code shouldn't run anyway.

If tabs is an absolute must let me know and i'll have another look.



来源:https://stackoverflow.com/questions/63193117/hidden-element-blocking-me-from-clicking-on-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!