2013-08-18 1 views
0

URL을 읽고 디스크에 쓰는 코드가 있습니다. 여기있다 -웹 사이트에서 pdf 파일 가져 오기 및 디스크에 쓰기

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 파일을 작성할 수 있습니다 위의 코드와

- 나는 다음과 같은 API를 사용할 때

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

내가 같은 오류를 - 내가 뭔가를 분명 실종처럼

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

는 느낌. 이것은 잘못 될 수 있습니다.

답변

1

ret.content이 아니고 ret.text이라고 쓰고 싶습니다. ret.text은 PDF를 유니 코드로 변환하려고 시도합니다. 이는 PDF와 같은 바이너리 형식에서는 불가능합니다.

또한 내장 함수를 사용할 수도 있습니다. 하위 레벨 os.open은 필요 없습니다.

+1

감사합니다. 나는 ret.contents가 있다는 것도 몰랐다. html로 .text를 사용했고 pdf에서도 그렇게 할 수 있다고 생각했습니다. .text가 유니 코드로 변환하려고 시도하는 것은 당연합니다. Btw 나는 내용이 아니라 내용이라고 생각합니다. 방금 확인 했어. – R11

+0

당신은'content'와'contents'에 대해 맞습니다. 이제 수정되었습니다. –

관련 문제