【问题标题】:Hidden element blocking me from clicking on button隐藏元素阻止我点击按钮
【发布时间】:2020-11-21 09:01:45
【问题描述】:

以下代码执行以下操作:

  1. 访问具有第一个日期的 URL
  2. 单击“跳过”关闭“了解起源”弹出窗口
  3. 点击“下载数据”按钮
  4. 用下一个日期打开一个新标签
  5. 关闭上一个选项卡(第一个日期 URL)
  6. 尝试再次点击“下载数据”

我遇到的问题是第 6 个问题。它给了我“元素点击被拦截”错误,我认为这是因为它认为出现了一个新的“了解起源”弹出窗口。

但是,这次没有弹出窗口,不像我第一次打开浏览器(FIRST date URL)。这次我什至尝试使用相同的代码单击“跳过”按钮,但它仍然给我同样的错误。

我怎样才能解决这个问题,并且每次打开新标签时都能点击“下载数据”按钮?注意:我在这里一次打开数千个标签。

我的代码:

# 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])

错误如下:

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)

【问题讨论】:

    标签: javascript python html selenium loops


    【解决方案1】:

    问题是您的驱动程序仍然专注于标签一。 当您打开一个新选项卡时,您需要将驱动程序更改为关注它。

    被拦截的点击是由上一个标签的下载弹出引起的。

    选项 1 改变这个:

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

    到这里:

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

    选项 2 或者,不要使用标签。 将execute_script 更改为此使用单个选项卡有效:

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

    实际上与以下内容相同:(也可以)

    driver.get(url)
    

    最后如果使用单个标签你就不需要这个了:

      # 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])
    

    但是 - 由于选项卡现在将始终为 1,因此这段代码不应该运行。

    如果标签是绝对必须让我知道,我会再看看。

    【讨论】:

    • 是的,我开始认为如果它不起作用,我可能不得不再次开始使用打开整个窗口。我只想使用标签,因为它们打开和关闭的速度更快,但我可以使用窗口。让我试一试......它的工作原理!但是,您知道为什么最后一个窗口打开需要这么长时间吗?即使在我删除了所有 time.sleep() 之后,我也不知道 try 和 except 是否会减慢它的速度。这可能吗?
    • 是否需要错误捕获?如果您删除它是否有效并且它是否更快?试试看:-)
    • 有效!!!我不敢相信。我真的很感谢你在我所有冗长而无聊的帖子中帮助我。太感谢了!如果我要修复的最后一件事实际上是代码执行 skip_button 事情所需的时间。我目前正在使用 time.sleep(6),但是每当我尝试使用 WebDriverWait 时,无论我在函数中输入的值如何,它都无法正常工作。它适用于 zone_type 下拉列表和 traffic_analysis_zones 变量。
    • 您尝试了哪些预期条件? - 你尝试过让元素可点击吗?
    • 预期条件是什么意思?嗯,是的,我希望跳过按钮是可点击的,但我猜 WebDriverWait 函数的重点是等到按钮准备好然后识别它,不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多