【问题标题】:save & load html response as object in a file - python将html响应保存并加载为文件中的对象-python
【发布时间】:2018-10-24 00:56:03
【问题描述】:

我的目标是保存和加载响应以供以后使用。 (可能是几天后)。 我想要高效而不是随时抓取网站,而是将它们保存为文件并在需要时加载它们。

import requests
from bs4 import BeautifulSoup

html = requests.get(link, timeout=5)
page_content = BeautifulSoup(html.content, "html.parser")

"""" Example of function that I would like to load the responce here instead."""

def getValue(page):
    return page.find('td', attrs={'class': 'Fz(s) Fw(500) Ta(end)'}).text

html 类型:

<class 'requests.models.Response'>

page_content 的类型:

<class 'bs4.BeautifulSoup'>

【问题讨论】:

    标签: python object python-requests python-object


    【解决方案1】:

    发出请求并将响应保存到文件:

    import requests
    
    r = requests.get(url)
    content = r.text
    
    with open('workfile', 'w') as f:
        f.write(content)
    

    当你需要访问之前保存的数据时:

    with open('workfile') as f:
       read_data = f.read()
    

    【讨论】:

    猜你喜欢
    • 2015-09-26
    • 1970-01-01
    • 2022-12-07
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多