【问题标题】:ElementClickInterceptedException when trying to select option in dropdown menu尝试在下拉菜单中选择选项时出现 ElementClickInterceptedException
【发布时间】:2023-03-27 16:51:01
【问题描述】:

我正在尝试从网站上获取不同床垫尺寸的一些价格,但问题是下拉菜单不是选择类型,它由一个带有 ul 不同选项列表的 div 组成,所以当我尝试点击一个选项它给了我这个错误。我能做什么?

这是我的代码:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from datetime import datetime
import time
import re
import logging
import traceback
from datetime import datetime, timedelta
import argparse
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy import exc
import mysql.connector as mysql
import io
import re

url ='https://thesleepcompany.in/product/mattress/smart-ortho/'

driver = webdriver.Chrome(options=options)
driver.get(url)
WebDriverWait(driver,15)
driver.find_element_by_css_selector('div.dk-selected.attached.enabled').click()
WebDriverWait(driver, 5)
opt= driver.find_element_by_css_selector('ul.dk-select-options').find_elements_by_tag_name('li')
driver.execute_script('arguments[0].setAttribute("class","dk-option attached enabled dk-option-selected")', opt[5])
driver.execute_script('arguments[0].setAttribute("aria-selected","true")', opt[5])
opt[5].click()
opt=driver.find_element_by_css_selector('ul.dk-select-options').find_elements_by_tag_name('li')
print_prices() #ignore it
print_price() #ignore it

这是我收到的完整错误消息:

ElementClickInterceptedException          Traceback (most recent call last)
<ipython-input-69-94877ec06aa4> in <module>
      4 driver.execute_script('arguments[0].setAttribute("class","dk-option attached enabled dk-option-selected")', opt[5])
      5 driver.execute_script('arguments[0].setAttribute("aria-selected","true")', opt[5])
----> 6 opt[5].click()
      7 opt=driver.find_element_by_css_selector('ul.dk-select-options').find_elements_by_tag_name('li')
      8 print_prices()

~\AppData\Local\Programs\Python\Python37\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):

~\AppData\Local\Programs\Python\Python37\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):

~\AppData\Local\Programs\Python\Python37\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))

~\AppData\Local\Programs\Python\Python37\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 <li class="dk-option attached enabled dk-option-selected" data-value="72%e2%80%b3-x-66%e2%80%b3-x-5%e2%80%b3" role="option" aria-selected="true" id="dk1-72%e2%80%b3-x-66%e2%80%b3-x-5%e2%80%b3">...</li> is not clickable at point (832, 483). Other element would receive the click: <div class="woocommerce-product-details__short-description">...</div>
  (Session info: chrome=91.0.4472.101)

【问题讨论】:

    标签: python-3.x selenium web-scraping


    【解决方案1】:

    我们不能使用Select 类,因为下拉菜单不是使用Selectoption 标签构建的。取而代之的是 Ul 和 li 标签:

    以下代码对我有用:

    driver.maximize_window()
    wait = WebDriverWait(driver, 10)
    driver.get("https://thesleepcompany.in/product/mattress/smart-ortho/")
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.dk-selected.attached.enabled"))).click()
    mat_to_select = '84\" x 36\" x 6" (Single)'
    print(len(driver.find_elements(By.CSS_SELECTOR, "div.dk-selected.attached.enabled+ul li")))
    for mat_size in driver.find_elements(By.CSS_SELECTOR, "div.dk-selected.attached.enabled+ul li"):
        if mat_size.text == mat_to_select:
            ActionChains(driver).move_to_element(mat_size).click().perform()
    

    进口:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.action_chains import ActionChains
    

    【讨论】:

    • 您好,很抱歉回复晚了,但不是像您那样指定尺寸,我可以直接从网页中获取尺寸列表,然后像在我的代码中那样遍历它吗?它会起作用吗?在我的代码中,我也尝试过使用 Actions,但它不起作用,它是随机的,有时它可能会起作用,有时它不会
    • 我可以直接从网页中获取尺寸列表,然后进行迭代 - 请参阅我的解决方案 print(len(driver.find_elements(By.CSS_SELECTOR, "div.dk-selected.attached.enabled+ul li"))) 中的这一行 - 这将打印我们在下拉列表中拥有的选项的大小。它是 29。它不是使用选项标签构建的,所以我们不能在这里使用索引。您的测试用例应该知道在执行之前选择哪个大小
    • 它抛出了与我的代码相同的错误,“ElementClickInterceptedError”或有时是“StaleReferenceError”。这就是为什么我问你是否尝试过。问题不在于单价。我需要各种尺寸的价格。有什么我可以做的吗?
    【解决方案2】:

    看看这是否有效:-

    driver.find_element_by_xpath(".//div[@class='dk-selected attached enabled']").click()
    
    listValues = driver.find_elements_by_xpath(".//ul[@class='dk-select-options']/li")
    fifthElm = listValues[4]
    
    driver.execute_script("arguments[0].click();",fifthElm)
    

    【讨论】:

    • 它有时会起作用:/ 就像曾经 id 是“dk1-combobox”但另一次它抛出错误,所以我检查并将 id 更改为“dk2-combobox”
    • 好的。更新了代码中使用的 xpath。看看这是否有效。
    • 没有没有用。我需要刮掉所有可用尺寸的价格。这适用于单个元素,但是当我尝试遍历列表时。它抛出一个 StaleElementReferenceError。
    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多