【问题标题】:Pdf to txt from http request从http请求的pdf到txt
【发布时间】:2014-12-04 06:40:31
【问题描述】:

我有一组指向 pdf 文件的链接:

https://www.duo.uio.no/bitstream/10852/9012/1/oppgave-2003-10-30.pdf

其中一些受到限制,这意味着我将无法访问 pdf 文件,而其他人将直接访问 pdf 文件本身,如上面的链接。

我目前正在使用请求包(python)来访问文件,但是有很多文件可供我下载,而且我也不想要 pdf 格式的文件。

我想做的是转到每个链接,检查链接是否为pdf文件,下载该文件(如果需要),将其转换为txt文件,并删除原始pdf文件。

我有一个非常好的 pdf 到 txt 转换器的 shell 脚本,但是可以从 python 运行 shell 脚本吗?

【问题讨论】:

    标签: python shell http pdf converter


    【解决方案1】:

    Kieran Bristow 有answered 部分关于如何从 Python 运行外部程序的问题。

    您问题的另一部分是关于通过检查资源是否为 PDF 文档来选择性地下载文档。除非远程服务器提供其文档的替代表示(例如文本版本),否则您将需要下载文档。为避免下载非 PDF 文档,您可以发送初始 HEAD 请求并查看回复标头以确定 content-type,如下所示:

    import os.path
    import requests
    
    session = requests.session()
    
    for url in [
        'https://www.duo.uio.no/bitstream/10852/9012/1/oppgave-2003-10-30.pdf',
        'https://www.duo.uio.no/bitstream/10852abcd/90121023/1234/oppgave-2003-10-30.pdf']:
        try:
            resp = session.head(url, allow_redirects=True)
            resp.raise_for_status()
            if resp.headers['content-type'] == 'application/pdf':
                resp = session.get(url)
                if resp.ok:
                    with open(os.path.basename(url), 'wb') as outfile:
                        outfile.write(resp.content)
                        print "Saved {} to file {}".format(url, os.path.basename(url))
                else:
                    print 'GET request for URL {} failed with HTTP status "{} {}"'.format(url, resp.status_code, resp.reason)
        except requests.HTTPError as exc:
            print "HEAD failed for URL {} : {}".format(url, exc)
    

    【讨论】:

    • 感谢您的链接和脚本。但是,当我运行脚本时,即使链接是有效的 pdf 文件,我也只会收到“HEAD failed for URL”异常。
    • @ArashSaidi - 奇怪,它适用于我使用该 URL。我注意到服务器有点奇怪,例如https://www.duo.uio.no/bitstream/10852/9012/1/oppgave-2003-10-30.txt 也返回一个 PDF。您使用的网址与我的回答中的网址相同吗?
    • 但是我有26546个链接,都返回错误信息。
    • 包含 exc 值的完整错误信息是什么?
    【解决方案2】:

    是的!完全可以从 python 运行 shell 脚本。看看 subprocess python 模块,它允许您创建进程,就像使用 shell 一样:https://docs.python.org/2/library/subprocess.html

    例如:

    import subprocess
    
    process = subprocess.Popen(["echo", "message"], stdout=subprocess.PIPE)
    
    print process.communicate()
    

    那里有很多教程,例如:http://www.bogotobogo.com/python/python_subprocess_module.php

    【讨论】:

    • 谢谢,会调查的。
    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多