【问题标题】:SecurityError: Permission denied to access property "document" on cross-origin object error clicking on download link in iframe using Selenium PythonSecurityError: Permission denied to access property "document" on cross-origin object error click on download link in iframe using Selenium Python
【发布时间】:2020-10-19 22:05:15
【问题描述】:

我正在从事一个自动化项目,我正在尝试从网站下载 pdf。该网站仅包含pdf,但网页的文件类型为HTML。 pdf 使用 PDF.js 显示,PDF.js 查看器也在 iframe 中。

当我尝试使用浏览器 javascript 单击元素时,返回一个与跨站点脚本相关的安全错误。

SecurityError: Permission denied to access property "document" on cross-origin object

我想从我的脚本中下载 pdf,该脚本是用 python 编写的,使用 selenium。当我尝试这个时:

driver.find_element_by_id('download').click()

没有产生任何结果,即使我已将焦点切换到 selenium 中的 iframe,下载按钮也不会被点击。

有人知道如何下载 pdf 的解决方案吗?

【问题讨论】:

    标签: python selenium iframe same-origin-policy cross-origin-read-blocking


    【解决方案1】:

    要点击元素,您必须将WebDriverWait 诱导为element_to_be_clickable(),您可以使用以下任一Locator Strategies

    • 使用ID

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "download"))).click()
      
    • 使用CSS_SELECTOR

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#download"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='download']"))).click()
      
    • 注意:您必须添加以下导入:

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

    参考

    您可以在以下位置找到详细讨论:

    【讨论】:

    • 我使用了您的代码:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "download"))).click() 但是我现在收到此错误:'Exception已发生:ElementClickInterceptedException' 我该如何解决这个问题?
    • @EC 你能用完整的错误跟踪日志更新问题吗?
    • @EC someIdsomeClasssomeJS 等不会帮助我改进答案。相关的 html 和准确的错误跟踪日志是解决方案的关键。
    • 修改后的问题。你知道如何避免这个错误吗?
    • @EC 定位器在问题中是 find_element_by_id('download'),因为错误中的定位器是 (By.ID, "ctl00_PH_AvailableReport1_UCAvailRpt_dgAvailableReport_ctl00_ctl06_lnkRptOpt")。您现在是否意识到发布基于相关文本的 HTML 是多么重要?
    猜你喜欢
    • 2019-07-30
    • 2020-10-09
    • 1970-01-01
    • 2020-03-09
    • 2015-05-08
    • 2017-12-25
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    相关资源
    最近更新 更多