有一个程序可以解析欧元和美元。
一切正常,但速度明显缓慢:该功能需要 3 到 5 秒......
from requests import get
from bs4 import BeautifulSoup as bs
def get_wal():
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Host":"myfin.by:443",
"Accept-Encoding": "gzip, deflate, sdch, br",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
}
body = get('https://myfin.by/currency/minsk', headers=headers)
for_bs = body.text
soup = bs(for_bs, 'html.parser')
usd_span = soup.find_all('span', {'class':'bl_usd_ex'})
usd = usd_span[0].text
eur_span = soup.find_all('span', {'class': 'bl_eur_ex'})
eur = eur_span[0].text
return usd, eur
我怎样才能加快速度?
显然,您运行脚本的服务器非常慢,或者白天站点上的负载更多。我只是通过 Google Colab 尝试过,大部分时间都是从网站加载页面,你无能为力。如果只是突然他们有一个 API 或一个移动版本,但我没有立即找到它。您唯一可以做的就是将解析器更改为
lxml
,它会更快一点:使用 Colab 中的这个解析器,大约需要 0.8 秒 - 页面加载,另外 0.5 秒 - 解析 BS,总共大约 1.5 秒,但即使使用您指定的解析器,在 Colab 中加载大约需要 1.7 秒。
从CrazyElf 的回答中扩展移动版主题:
运行时测试:
使用 lxml 作为解析器的变体:
将加快处理速度: