2017-11-04 109 views
0

我想從NSE印度網站下載數據。要下載的數據是我下載後處理的zip文件。 其下載的日期的文件,一年後2016年使用urllib2禁止訪問403一些URL python

def start_download(): 

    directory = 'data' 
    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) ' 
         'Chrome/23.0.1271.64 Safari/537.11', 
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
      'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 
      'Accept-Encoding': 'none', 
      'Accept-Language': 'en-US,en;q=0.8', 
      'Connection': 'keep-alive'} 
    try: 
     #req = urllib2.Request("https://www.nseindia.com/content/historical/EQUITIES//2000/JAN/cm01JAN2000bhav.csv.zip", headers=hdr) 
     import ipdb;ipdb.set_trace() 
     req = urllib2.Request("https://www.nseindia.com/content/historical/EQUITIES//2017/NOV/cm03NOV2017bhav.csv.zip", headers=hdr) 
     file_url = urllib2.urlopen(req) 
     try: 
      if not os.path.exists(directory): 
       os.makedirs(directory) 
      file_name_obj = open(os.path.join(directory, "hello.zip"), 'wb') 
      file_name_obj.write(file_url.read()) 
      file_name_obj.close() 
     except IOError, e: 
      print e 
    except Exception, e: 
     print e 

在上面的代碼,當我使用的URL「https://www.nseindia.com/content/historical/EQUITIES//2017/NOV/cm03NOV2017bhav.csv.zip」我的示例代碼,它下載數據。我也嘗試使用郵差客戶端,它也下載。

當我使用以下網址:https://www.nseindia.com/content/historical/EQUITIES//2000/JAN/cm01JAN2000bhav.csv.zip時,我在代碼以及郵遞員中獲得了禁止訪問403錯誤。當我在Chrome瀏覽器中粘貼此鏈接時,也存在問題。

但是,當經過從該頁面「https://www.nseindia.com/products/content/equities/equities/archieve_eq.htm」鏈接,並把ReportBhavcopydate爲2000年1月1日,它成功地下載文件* .csv.zip。

如何解決此示例代碼中的註釋URL的403禁止錯誤?

回答

0

您需要調整標題。 這裏是如何做到這一點,以及如何編寫使用Python下載的文件的例子:

from urllib.request import Request, urlopen 
import shutil 

link = 'https://www.nseindia.com/content/historical/EQUITIES//2017/NOV/cm03NOV2017bhav.csv.zip' 
header = { 
    'Accept-Encoding': 'gzip, deflate, sdch, br', 
    'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4', 
    'Host': 'www.nseindia.com', 
    'Referer': 'https://www.nseindia.com/', 
    'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36', 
    'X-Requested-With': 'XMLHttpRequest' 
} 

def download_file(link, file_name, length): 
    try: 
     req = Request(link, headers=header) 
     with open(file_name, 'wb') as writer: 
      request = urlopen(req, timeout=3) 
      shutil.copyfileobj(request, writer, length) 
    except Exception as e: 
     print('File cannot be downloaded:', e) 
    finally: 
     print('File downloaded with success!') 

file_name = 'new_file.zip' 
length = 1024 
download_file(link, file_name, length) 

最後,您可以檢查是否使用這種方法下載的文件與下載的文件相同的SHA1和你瀏覽器:使用

文件下載的Python:

> sha1sum cm03NOV2017bhav.csv.zip 
daff49646d183636f590db6cbf32c93896179cb2 cm03NOV2017bhav.csv.zip 
:使用鉻

> sha1sum new_file.zip 
daff49646d183636f590db6cbf32c93896179cb2 new_file.zip 

文件下載