首页 > 解决方案 > 在本地保存 requests.get() 响应以在 Beautiful Soup 中使用

问题描述

因此,我正在构建一个 Python 脚本,以使用 Requests 和 BeautifulSoup4 从 url 中抓取一些数据(世界杯比分),并且在测试我的代码时,我发出的请求比网站想要的多,从而定期导致此错误:

 requests.exceptions.ConnectionError: Max retries exceeded with url

我实际上不需要一直调用该页面,当然我只需要调用一次并将返回的数据保存在本地并将其输入到美丽的汤中。当然我不是第一个这样做的人,还有其他方法吗?这可能是微不足道的,但我对此很陌生-谢谢。

这是我正在使用的:

import requests
from bs4 import BeautifulSoup

url = "https://www.telegraph.co.uk/world-cup/2018/06/26/world-cup-2018-fixtures-complete-schedule-match-results-far/"
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")

标签: pythonweb-scrapingbeautifulsouppython-requests

解决方案


将 HTML 存储在一个文件中一次:

response = requests.get(url)
with open('cache.html', 'wb') as f:
    f.write(response.content)

然后,下一次,只需从文件中加载它:

with open('cache.html', 'rb') as f:
    soup = BeautifulSoup(f.read(), 'html.parser')

推荐阅读