如何使用Python通过mechanize实现网页抓取后的结果缓存

cty*_*neg 2 python caching mechanize web-scraping

我的网页抓取脚本是用 Python 编写的,利用了 mechanize。这就是我的脚本的样子:(替换了敏感信息)

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
Run Code Online (Sandbox Code Playgroud)

登录后,我的 get_information() 方法检索商店位置列表,并将它们切成我想要的位置后,将它们保存到字典位置中。此方法在我使用 Flask 构建的网站中调用,目前在本地主机上运行。这是我的网站代码中的调用位置:

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

该列表随后显示在我网站上的下拉菜单中,供用户选择一个选项。

我的问题是如何对从 get_information() 方法收到的结果实现缓存,因为我不想每次用户访问网页(使用信息的地方)时都执行网页抓取(这是相当频繁的,因为它是主页之一)。我曾尝试寻找如何实现缓存,但由于我对此还很陌生,因此我无法理解需要做什么。如果有人能给我指出相关的例子,我将不胜感激!

谢谢你!:)

Jar*_*ber 5

如果其他人访问此线程,则在抓取时(如果您正在使用requests)进行缓存的另一个不错的选择是requests-cache模块。

它是一个插件requests,经过几行配置后,它将为您处理缓存。

import requests
import requests_cache

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

# use requests as usual
Run Code Online (Sandbox Code Playgroud)

如上面的示例所示,该模块允许我们轻松定义缓存名称、后端和过期时间。