这个简单的Python 3脚本:
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
我认为这可能是暂时的问题,所以我添加了一些简单的异常处理,如so:
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...
。
您的URL返回403代码错误,显然urllib.request.urlretrieve不善于检测所有的HTTP错误,因为它正在使用^{} 和最近的尝试通过返回
urlinfo
而不是引发错误来吞咽错误。关于修复,如果您仍然想使用urlretrieve,您可以这样覆盖FancyURLopener(包含的代码也显示了错误):
否则,我建议您使用^{} 这样:
相关问题 更多 >
编程相关推荐