用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()方法收到的結果的緩存,因爲我不想每次訪問網頁(使用信息的地方)都要執行網頁抓取由用戶(這是相當頻繁的,因爲它是主頁之一)。我試圖尋找如何實現緩存,但由於我對此仍然很陌生,因此我無法理解需要做什麼。如果有人能指點我一個相關的例子,將不勝感激!
謝謝! :)
謝謝@Greg會試試這個方法:) – ctyneg 2014-12-22 01:29:30