2012-07-17 23 views
6

この単純なのPython 3スクリプト:ValueErrorを修正するにはどうすればよいですか?クローズファイル例外の読み取り?

import urllib.request 

host = "scholar.google.com" 
link = "/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0" 
url = "http://" + host + link 
filename = "cite0.bib" 
print(url) 
urllib.request.urlretrieve(url, filename) 

は、この例外が発生します:

Traceback (most recent call last): 
    File "C:\Users\ricardo\Desktop\Google-Scholar\BibTex\test2.py", line 8, in <module> 
    urllib.request.urlretrieve(url, filename) 
    File "C:\Python32\lib\urllib\request.py", line 150, in urlretrieve 
    return _urlopener.retrieve(url, filename, reporthook, data) 
    File "C:\Python32\lib\urllib\request.py", line 1597, in retrieve 
    block = fp.read(bs) 
ValueError: read of closed file 

私は、これは一時的な問題かもしれないと思ったので、私はそうのように扱ういくつかの簡単な例外を追加しました:

import random 
import time 
import urllib.request 

host = "scholar.google.com" 
link = "/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0" 
url = "http://" + host + link 
filename = "cite0.bib" 
print(url) 
while True: 
    try: 
     print("Downloading...") 
     time.sleep(random.randint(0, 5)) 
     urllib.request.urlretrieve(url, filename) 
     break 
    except ValueError: 
     pass 

しかし、これはちょうどDownloading...を無限に印刷します。

+0

「http:// scholar.google.com/robots.txt」を見ると、Googleがこのページの自動ダウンロードを禁止していることがわかります。 'wget'を使ってみると' 403 Forbidden'というエラーが出ます。私はこれもあなたのスクリプトに起こっていると思う。 –

+0

@sendle APIはないので、私はそれを手動で解析しています。 –

+0

@ senderle、おそらくあなたはコンテンツを取得するためにクッキーを送信する必要があります。 –

答えて

4

あなたのURLは403コードのエラーを返し、それがurllib.request.FancyURLopenerurlinfoを返す代わりに、エラーを発生させることで、エラーを飲み込むために、この最新の試みを使用しているため、明らかurllib.request.urlretrieveは、すべてのHTTPエラーを検出するのが得意ではありません。修正について

あなたはまだあなたがこの(コードは、エラーを表示するために含まれている)のようにはFancyURLopenerをオーバーライドすることができますurlretrieve使用したい場合:

エルス
import urllib.request 
from urllib.request import FancyURLopener 


class FixFancyURLOpener(FancyURLopener): 

    def http_error_default(self, url, fp, errcode, errmsg, headers): 
     if errcode == 403: 
      raise ValueError("403") 
     return super(FixFancyURLOpener, self).http_error_default(
      url, fp, errcode, errmsg, headers 
     ) 

# Monkey Patch 
urllib.request.FancyURLopener = FixFancyURLOpener 

url = "http://scholar.google.com/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0" 
urllib.request.urlretrieve(url, "cite0.bib") 

と、これは私はあなたがurllib.request.urlopenを使用することができますお勧め何ですlike:

fp = urllib.request.urlopen('http://scholar.google.com/scholar.bib?q=info:K7uZdMSvdQ0J:scholar.google.com/&output=citation&hl=en&as_sdt=1,14&ct=citation&cd=0') 
with open("citi0.bib", "w") as fo: 
    fo.write(fp.read()) 
+0

助けてくれてありがとう。 +1し、猿のパッチ適用と一般的な助けを受け入れることができます。私はそれ以来、上記のコメントに従って、 'robots.txt'はこれらのファイルをダウンロードすることを禁じています。私はそれを確認することを完全に忘れてしまった。 –

関連する問題