2014-12-19 53 views
1

用Python編寫,我的網頁抓取腳本使用機械化。這是我的腳本看起來像:(替換爲敏感信息)如何在使用Python機械化網頁抓取後實現結果緩存

import mechanize 
import cookielib 
from bs4 import BeautifulSoup 
import html2text 
import json 

br = mechanize.Browser() 
cj = cookielib.LWPCookieJar() 
br.set_cookiejar(cj) 
br.set_handle_equiv(True) 
br.set_debug_responses(True) 
br.set_handle_gzip(True) 
br.set_handle_redirect(True) 
br.set_handle_referer(True) 
br.set_handle_robots(False) 
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) 
br.addheaders = [('User-agent', 'Safari/8.0')] 
br.open('https://example.com/login.jsp') 
for f in br.forms(): 
    print f 
br.select_form(nr=0) 
br.form['u'] = 'abcd' 
br.form['p'] = '1234' 
br.submit() 

def get_information(): 
    locations=[] 
    data=json.load(br.open('https://example.com/iWantThisJson.jsp')) 
    for entry in data["stores"]: 
     location=entry["name"].split("(",1)[0] 
     locations.append(location) 
    return locations 

登錄後,我get_information()方法檢索商店位置的列表和切片他們到我想要的東西后,我將它們保存到字典locations.This方法被稱爲在我的網站建立與Flask,目前在本地運行。這裏是它被稱爲在我的網站代碼:

class reportDownload(Form): 
    locations={} 
    locations=get_information() 
    locations_names=list(enumerate(locations)) 
    location=SelectField(u'Location',choices=locations_names) 

這份名單是不是顯示在下拉菜單上我的網站,讓用戶選擇一個選項。

我的問題在於如何去執行從我的get_information()方法收到的結果的緩存,因爲我不想每次訪問網頁(使用信息的地方)都要執行網頁抓取由用戶(這是相當頻繁的,因爲它是主頁之一)。我試圖尋找如何實現緩存,但由於我對此仍然很陌生,因此我無法理解需要做什麼。如果有人能指點我一個相關的例子,將不勝感激!

謝謝! :)

回答

1

有很多簡單的方法來實現緩存。

  1. 將數據寫入文件。如果你只是處理少量的數據,這特別容易。 JSON blob也可以輕鬆寫入文件。

    with open("my_cache_file", "a+") as file_: file_.write(my_json_blob)

  2. 使用鍵值存儲緩存像Redis的數據。 Installing redis很簡單。使用它也非常簡單。有一個非常良好的書面python client for redis

    redis=redis.StrictRedis() redis.set(key, json_blob) json_blob = redis.get(key)

  3. 您還可以使用類似的Postgres,MongoDB的,MariaDB的,或任何常用的數據庫,將數據存儲到磁盤上,但只有當你的數據是如此之大,這是它極大地outscaling你有你的計算機上的內存量刮時(如果你使用requests)(Redis的寫入內存)

+0

謝謝@Greg會試試這個方法:) – ctyneg 2014-12-22 01:29:30

0

萬一別人訪問此線程,另一個很好的選擇對於緩存requests-cache模塊。

它是一個requests的插件,並且在配置幾行後,將爲您處理緩存。

import requests 
import requests_cache 

requests_cache.install_cache('name/of/cache' 
          backend='mongdb', 
          expire_after=3600) 

# use requests as usual 

如在上面的例子中所示,模塊允許我們很容易地定義一個高速緩存名,後端,和過期時間。