通过单击硒中的关闭按钮来关闭弹出窗口

时间:2020-03-18 11:07:30

标签: python selenium selenium-webdriver

我想关闭当我点击特定网址时出现的弹出窗口。这是该页面的“检查元素”窗口:

enter image description here

这是我尝试过的:

public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {

  @Override
  public Response toResponse(JsonMappingException e) {   
      Error error = new Error();
      error.setFieldName(propertyPath);
      error.setMessage(NOT_VALID_VALUE);
      error.setDescription("Can not understand the request");

      ABCError exception = new ABCError();
      exception.setHttpStatus(Response.Status.BAD_REQUEST.getStatusCode());
      exception.setDatetime(LocalDateTime.now());
      exception.setType(CLIENT_EXCEPTION);
      exception.setMessage(EXCEPTION_W_DETAILS_MESSAGE);
      exception.setErrors(Collections.singletonList(error));

      return Response.status(exception.getHttpStatus())
            .entity(exception)
            .build();
}

但是它给出了以下错误:

InvalidSelectorException:消息:给出了CSS选择器表达式 “ i [@ class ='popupCloseIcon']”无效:InvalidSelectorError: Document.querySelector:'i [@ class ='popupCloseIcon']'无效 选择器:“ i [@ class ='popupCloseIcon']”

以下是显示弹出窗口的网址:https://www.investing.com/equities/oil---gas-dev-historical-data 通过硒打开URL后,将在几秒钟后显示弹出窗口。 如何单击该关闭按钮?

3 个答案:

答案 0 :(得分:2)

一段时间后会出现弹出窗口,因此您需要等待解决此问题。而且您的选择器无效:i[@class='popupCloseIcon'],请使用i[class*='largeBannerCloser']

image close

请尝试以下操作:

driver.get('https://www.investing.com/equities/oil---gas-dev-historical-data')

try:
    popup = WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "i[class*='largeBannerCloser']")))
    popup.click()
except TimeoutException as to:
    print(to)

这要等到最长60秒。

正在导入:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

答案 1 :(得分:1)

在访问URL https://www.investing.com/equities/oil---gas-dev-historical-data以关闭弹出窗口几秒钟后弹出窗口出现时,您需要为element_to_be_clickable()引入 WebDriverWait ,您可以使用以下Locator Strategies中的

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "i.popupCloseIcon.largeBannerCloser"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//i[@class='popupCloseIcon largeBannerCloser']"))).click()
    
  • 注意:您必须添加以下导入:

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

答案 2 :(得分:0)

首先,“ i [@ class ='popupCloseIcon']”是无效的CSS选择器定位符,应为“ i [class ='popupCloseIcon']”。其次,有四个元素映射到“ i [class ='popupCloseIcon']”,css选择器“ div.right> i.popupCloseIcon”将帮助您找到目标元素

相关问题