python - 如何让 python webscraping 更好地更新
问题描述
我正在尝试制作一个 python 股票价格检查器。它运行良好,但更新非常缓慢。它不断运行并从https://money.cnn.com获取信息。
import requests, time, os
from bs4 import BeautifulSoup as bs
import simpleaudio as sa
original = 0
while True:
pfe = requests.get('https://money.cnn.com/quote/quote.html?symb=pfe')
soup = bs(pfe.content, 'lxml').body
price_pfe = soup.find('td', {'class':'wsod_last'}).span.contents[0]
if (price_pfe != original):
print("Pfizer price: " + price_pfe)
original = price_pfe
有什么技巧可以让它更新得更快吗?
解决方案
仅使用 lxml 和 xpath 而不是 bs 获胜两次
import requests, time
from lxml import html
original = 0
while True:
start_time = time.time()
pfe = requests.get('https://money.cnn.com/quote/quote.html?symb=pfe')
tree = html.fromstring(pfe.content)
price_pfe = float(tree.xpath("//td[@class='wsod_last']/span")[0].text_content().strip())
print(price_pfe)
if (price_pfe != original):
print("Pfizer price: " + str(price_pfe))
original = price_pfe
print("--- %s seconds ---" % (time.time() - start_time))
推荐阅读
- flutter - 如何使用键盘完成按钮 Flutter、observable、streamBuilder 实现验证
- docker - 如何在我的计算机上本地托管 Web 应用程序
- c++ - 为什么读取缓冲区时 read() 会无限期阻塞
- next.js - NextJS 动态 urls 查询不传回 ID
- r - 展开为空白并取消嵌套
- javascript - 当 npm 开始使用 express 和 nodemon 时应用程序崩溃
- php - WordPress: Add page to Yoast SEO breadcrumbs
- python - 两个for循环的优化
- gradle - 没有可用于离线模式的 com.android.tools.build:aapt2:3.6.1-6040484 缓存版本
- python - 如何从列表的每个元素中创建一个变量?