【问题标题】:Downloading PDF from popup/form with Selenium Python ChromeDriver使用 Selenium Python ChromeDriver 从弹出窗口/表单下载 PDF
【发布时间】:2019-05-04 09:12:53
【问题描述】:

无法确定下一步,尝试从网站下载 pdf 文件并卡住。

https://www.southtechhosting.com/SanJoseCity/CampaignDocsWebRetrieval/Search/SearchByElection.aspx

Page with Links to PDF Files

PDF file to download

我能够使用 Selenium 和 ChromeDriver 从“带有链接的页面”中单击 pdf 链接,但随后我得到一个弹出表单而不是下载。

我尝试禁用 Chrome PDF 查看器 ("plugins.plugins_list":[{"enabled":False,"name":"Chrome PDF Viewer"}]),但这不起作用。

弹出表单(在“要下载的 PDF 文件”中查看)有一个悬停链接来下载 pdf 文件。我已经尝试过 ActionChains(),但运行此行后出现此异常:

from selenium.webdriver.common.action_chains import ActionChains

element_to_hover = driver.find_element_by_xpath("//paper-icon-button[@id='download']")
hover = ActionChains(driver).move_to_element(element_to_hover)
hover.perform()

寻找在这种情况下下载 pdf 文件的最有效方法。谢谢!

【问题讨论】:

  • 检查 here 并禁用 chrome 中的 pdf 查看器。然后,当您单击打开弹出窗口的元素时,将为您提供指向实际文件的链接。在新选项卡中打开该链接,它应该会下载文件。
  • 已经试过了,还是不行。我得到一个空白表格,没有下载
  • 什么对你不起作用,禁用 pdf 查看器或后面的部分?当禁用 pdf 查看器时,我可以看到这样的元素 <a href="PdfHandler.axd?key=899d7d22b1aa42fe83ffbeaafbb9f647PdfDownloadSessionKey&download=True&fileName=Form">Click here</a> 在新选项卡中打开时会下载文件。
  • 我明白你的意思,但是当我尝试访问弹出表单中的元素时,我遇到了同样的问题。 driver.find_element_by_link_text("Click Here").click() --> NoSuchElementException: 无法找到“单击此处”...

标签: python selenium selenium-chromedriver


【解决方案1】:

请试试这个:

chromeOptions = webdriver.ChromeOptions()
prefs = {"plugins.always_open_pdf_externally": True}
chromeOptions.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.get('https://www.southtechhosting.com/SanJoseCity/CampaignDocsWebRetrieval/Search/SearchByElection.aspx')

#Code to open the pop-up
driver.find_element_by_xpath('//*[@id="ctl00_DefaultContent_ASPxRoundPanel1_btnFindFilers_CD"]').click()
driver.find_element_by_xpath('//*[@id="ctl00_GridContent_gridFilers_DXCBtn0"]').click()
driver.find_element_by_xpath('//*[@id="ctl00_DefaultContent_gridFilingForms_DXCBtn0"]').click()

driver.switch_to.frame(driver.find_element_by_tag_name('iframe'))
a = driver.find_element_by_link_text("Click here")
ActionChains(driver).key_down(Keys.CONTROL).click(a).key_up(Keys.CONTROL).perform()

更新: 要退出弹出窗口,您可以尝试以下操作:

driver.switch_to.default_content()
driver.find_element_by_xpath('//*[@id="ctl00_GenericPopupSizeable_InnerPopupControl_HCB-1"]/img').click()

【讨论】:

  • 工作就像一个魅力,需要习惯 xpath。感谢您的帮助!
  • 快速提问,下载pdf文件后如何退出弹出窗口?我试过ActionChains(driver).send_keys(Keys.ESCAPE).perform(),但我认为下载在帧上有一些变化。下载后关闭弹出窗口是否有更优雅的方法?
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 2018-09-12
  • 2017-12-19
相关资源
最近更新 更多