簡體   English   中英

從網站獲取pdf文件並寫入磁盤

[英]Getting a pdf file from a website and writing to disk

我有一些讀取URL並將其寫入磁盤的代碼。 這里是 -

    url = 'http://www.cs.purdue.edu/homes/ninghui/courses/Spring06/lectures/lecture05.pdf'
    ret = requests.get(url)
    print ret.headers
    print ret.headers['content-encoding']
    print ret.headers['content-type']

    pathToWrite = 'tmp/test.pdf'

    try:
        fd = os.open(pathToWrite, os.O_RDWR | os.O_CREAT)

        try:
            os.write(fd, ret.text)
        except Exception as e:
            print 'cannot write to file ' + pathToWrite
            raise

        try:
            os.close(fd)
        except:
            print 'cannot close file ' + pathToWrite
            raise

    except:
        print 'file cannot be opened ' + pathToWrite
        raise

使用上面的代碼,我可以獲取並向磁盤寫入pdf文件,出現以下錯誤-

UnicodeEncodeError: 'charmap' codec can't encode characters in position 12-13: character maps to <undefined>

使用以下API時出現相同的錯誤-

f = open(pathTowWrite, 'wb')
f.write(ret.text)

我覺得我缺少明顯的東西。 這似乎太簡單了,不會出錯。

您要編寫ret.content而不是ret.text ret.text嘗試將PDF轉換為Unicode,這對於像PDF這樣的二進制格式來說可能是不可能的。

另外,您可以只使用內置的打開功能。 無需此處的低級os.open

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM