首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Selenium在浏览器中打开保存pdf

使用Selenium在浏览器中打开保存pdf
EN

Stack Overflow用户
提问于 2018-09-06 20:23:31
回答 1查看 1.5K关注 0票数 3

因此,我登录到我公司拥有的一个web应用程序,运行一个生成pdf的请求,这都是在python中使用驱动程序完成的。我只能使用IE,因为公司系统不能与任何其他浏览器一起工作。

一旦我提交请求,一个新的IE窗口弹出与我要求的pdf文件。我想把pdf文件保存到我的电脑上。我意识到在IE中使用下载并不容易,但是必须有一个方法。我也同意将其保存为png或任何其他格式,但pdf很长(通常为2-5页),因此打印屏幕或屏幕截图将无法工作。

对我能做什么有什么建议吗?

下面是代码的一个简单片段:

代码语言:javascript
复制
driver.implicitly_wait(5)

driver.find_element_by_name("invNumSrchTxt_H").send_keys("ABCDE")  #sending the parameters I need
driver.find_element_by_name("invDt_B").clear()  # Clearing out some preset params
driver.find_element_by_name("invDt_A").clear()


 # This is where I click the button and this pops open a new IE window with my pdf file in it.
 s=driver.find_element_by_name("Print_Invoice")
 s.click()
EN

回答 1

Stack Overflow用户

发布于 2018-09-07 07:33:37

您可以使用请求直接发送请求,因为IE不支持设置配置,您应该处理弹出窗口。

一项可能的执行可以是:

代码语言:javascript
复制
import requests


def download_pdf_file(url, filename=None, download_dir=None):
    """
    Download pdf file in url,
    save it in download_dir as filename.
    """
    if download_dir is None: # set default download directory
        download_dir = r'C:\Users\{}\Downloads'.format(os.getlogin())

    if filename is None: # set default filename available
        index = 1
        while os.path.isfile(os.path.join(download_dir, f'pdf_{index}')):
            index += 1
        filename = os.path.join(download_dir, f'pdf_{index}')

    response = requests.get(url) # get pdf data
    with open(os.path.join(download_dir, filename), 'wb') as pdf_file:
        pdf_file.write(response.content) # save it in new file


driver.implicitly_wait(5)

driver.find_element_by_name("invNumSrchTxt_H").send_keys("ABCDE")  #sending the parameters I need
driver.find_element_by_name("invDt_B").clear()  # Clearing out some preset params
driver.find_element_by_name("invDt_A").clear()


# This is where I click the button and this pops open a new IE window with my pdf file in it.
s=driver.find_element_by_name("Print_Invoice")
s.click()

driver.download_pdf_file = download_pdf_file

driver.download_pdf_file(driver.current_url, # pdf url of the new tab
                  filename='myfile.pdf', # custom filename
                  download_dir='') # relative path to local directory
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52211657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档