này đơn giản Python 3 kịch bản:Làm cách nào để sửa một ValueError: đọc ngoại lệ của tệp đã đóng?
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)
tăng ngoại lệ này:
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
Tôi nghĩ điều này có thể là một vấn đề tạm thời, vì vậy tôi đã thêm một số ngoại lệ đơn giản xử lý như sau:
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
nhưng điều này chỉ in Downloading...
vô hạn.
Nếu bạn tìm trong 'http: // scholar.google.com/robots.txt' bạn có thể thấy rằng Google cấm tải xuống tự động trang này. Và nếu bạn thử sử dụng 'wget', bạn sẽ gặp lỗi' 403 Forbidden'. Tôi nghi ngờ điều này cũng xảy ra với kịch bản của bạn. –
@senderle Không có API, vì vậy tôi sẽ phân tích cú pháp theo cách thủ công. –
@senderle, rất có thể bạn cần gửi cookie để tải nội dung. –