【发布时间】:2015-04-20 01:36:05
【问题描述】:
我正在尝试下载与研究人员相关的所需 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."
【问题讨论】:
-
你真的看过文件内容了吗?
-
其实我检查了下载链接,它们是错误的目录。现在我解决了这个问题,谢谢!但是修复目录意味着这个程序不能普遍使用,这是我正在努力解决的问题。
标签: file python-2.7 pdf download python-requests