python - 在本地保存 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")
解决方案
将 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')
推荐阅读
- python - 获取符合条件的组合
- c# - 从 C# 中的 REST 服务下载文件
- python - psycopg2 连接到数据库集群中的主服务器
- javascript - 在嵌套数组中查找空数组并在 Javascript 中删除它们
- javascript - expo-service-worker.js:93 未捕获的 DOMException:无法在“WorkerGlobalScope”上执行“importScripts”:
- php - 会话变量偶尔丢失
- typescript - postgresql typeOrm 过滤多对多关系
- php - Xero PHP API 错误:“您无权访问此资源”
- owl - 在 Protege 中根据对象属性按照一定的规则对个体进行分类
- java - 将阿拉伯数字转换为罗马数字的问题