2015-04-20 189 views
0

我正在嘗試下載與研究人員相關的所需PDF文件。無法打開下載的PDF文件

但是下載的PDF文件無法打開,說文件可能損壞或格式錯誤。而在測試中使用的另一個URL導致正常的PDF文件。你有什麼建議嗎?

import requests 
from bs4 import BeautifulSoup 


def download_file(url, index): 
    local_filename = index+"-"+url.split('/')[-1] 
    # NOTE the stream=True parameter 
    r = requests.get(url, stream=True) 
    with open(local_filename, 'wb') as f: 
     for chunk in r.iter_content(chunk_size=1024): 
      if chunk: # filter out keep-alive new chunks 
       f.write(chunk) 
       f.flush() 
    return local_filename 


# For Test: http://ww0.java4.datastructures.net/handouts/ 
# Can't open: http://flyingv.ucsd.edu/smoura/publications.html 

root_link="http://ecal.berkeley.edu/publications.html#journals" 

r=requests.get(root_link) 
if r.status_code==200: 
    soup=BeautifulSoup(r.text) 
    # print soup.prettify() 
    index=1 
    for link in soup.find_all('a'): 
     new_link=root_link+link.get('href') 
     if new_link.endswith(".pdf"): 
      file_path=download_file(new_link,str(index)) 
      print "downloading:"+new_link+" -> "+file_path 
      index+=1 
    print "all download finished" 
else: 
    print "errors occur." 
+0

你真的看過文件內容嗎? –

+0

其實我查了下載鏈接,他們是錯誤的目錄。現在我解決了這個問題,謝謝! 但修復目錄意味着這個程序不能被普遍使用,這是我試圖弄清楚的一個問題。 – ZoeZ

回答

0

代碼有評論說:

# Can't open: http://flyingv.ucsd.edu/smoura/publications.html

看起來像什麼,你不能打開是一個HTML文件。所以難怪PDF閱讀器會抱怨它...

對於任何真正的PDF鏈接,我有一個問題,我將進行如下:用不同的方法

  1. 下載文件(wgetcurl,瀏覽器,...)。
    • 你能下載它嗎?還是有一些密碼圈被跳過?
    • 下載速度快嗎?
  2. 是否然後在PDF查看器打開?
    • 如果是這樣,請與腳本下載的文件進行比較。
      • 有什麼區別?
      • 它們可能是由腳本引起的嗎?
      • 前幾百行內容沒有差異,但後來有區別嗎?文件結尾是一堆零字節?那麼你的下載沒有完成...
    • 如果不是這樣,仍然比較差。如果沒有,您的腳本沒有錯。 PDF可能確實被破壞...
  3. 在文本編輯器中打開時它看起來像什麼?
+0

該OP的腳本試圖從該文件下載所有*參考* – mkl

+0

是的,其實我試圖下載這個root_link頁面中的所有鏈接的PDF文件。 – ZoeZ