【问题标题】:Selenium TimeoutException when trying to click Cookies Agree尝试单击 Cookie 时出现 Selenium TimeoutException 同意
【发布时间】:2021-06-29 19:13:30
【问题描述】:

我正在尝试从网站上抓取一些文章,在此之前,我需要在 Python 中使用 Selenium 单击“Cookies Agree”。

但不幸的是,我不断收到 TimeoutException 或 NoSuchElementException!

我发现点击按钮在 iframe 中,所以我切换到它并点击了同意按钮。

homepage = 'link'
driver.maximize_window()
driver.get(homepage)
driver.implicitly_wait(5)

driver.switch_to.frame('location')

try:
  consent = wait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, 'classname')))
  consent.click()
except TimeoutException :
  print('timeoutexception')

driver.switch_to.default_content()

iframe

consent click button

但我仍然无法通过 TimeoutException 错误。

我做错了什么......?!

【问题讨论】:

  • 请查看我的回答

标签: selenium timeoutexception


【解决方案1】:

你搞砸了 waitdriver 对象。它们不一样。切换到 iframe 并等待您的按钮。

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


#  switch to frame here

wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, '.message-component.message-button.no-children:nth-of-type(2)')))
consent = driver.find_element_by_css_selector('.message-component.message-button.no-children:nth-of-type(2)')
consent.click()

有两个 .message-component.message-button.no-children css 定位器,您需要第二个。

要查找 iframe 的使用(这是防弹的):

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@id,'sp_message_iframe_')]"))

【讨论】:

  • 哦,哇!我不知道我弄乱了两个不同的对象。人们似乎可以互换使用它们,所以我只是假设我可以那样使用它。谢谢!
  • 是的,当然!但是你能帮我解决“NoSuchFrameException”吗?更正代码后,我得到“NoSuchFrameException:消息:sp_message_iframe_216133”。我之前没有收到这样的错误...
  • 好的,框架的定位器是动态的。我帮你搞定
  • “wait = WebDriverWait(driver, 20)”中是否存在语法错误?我一定是做错了什么,因为突然出现语法错误...
  • 以此为模板:wait = WebDriverWait(driver, 20) wait.until(EC.element_to_be_clickable((SelectBy.CSS_SELECTOR, "your_css")))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 2017-06-25
相关资源
最近更新 更多