使用Selenium Python ChromeDriver从弹出窗口/表单下载PDF

时间:2018-12-03 04:44:34

标签: python selenium selenium-chromedriver

无法确定下一步,尝试从网站下载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 Viewer(“ 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()

enter image description here

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

1 个答案:

答案 0 :(得分: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()