如何使用多线程简化以下python代码

2024-10-03 21:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的python代码,它从yahoo finance获取实时股票数据并将其更新到excel工作表中…是否有人通过使用多线程来简化它以提高性能(以便它同时更新excel单元格)…下面是代码

import bs4
import requests
import xlwings as xw
from multiprocessing import Process

from bs4 import BeautifulSoup

def bajparsePrice():
    baj_r=requests.get('https://in.finance.yahoo.com/quote/BAJFINANCE.NS/')
    baj_soup=bs4.BeautifulSoup(baj_r.text,"lxml")
    baj_price=baj_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return baj_price

def infyparsePrice():
    infy_r=requests.get('https://in.finance.yahoo.com/quote/INFY.NS/')
    soup=bs4.BeautifulSoup(infy_r.text,"lxml")
    infy_price=soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return infy_price

def relparsePrice():
    rel_r=requests.get('https://in.finance.yahoo.com/quote/RELIANCE.NS/')
    rel_soup=bs4.BeautifulSoup(rel_r.text,"lxml")
    rel_price=rel_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return rel_price

def sbinparsePrice():
    sbin_r=requests.get('https://in.finance.yahoo.com/quote/SBIN.NS/')
    sbin_soup=bs4.BeautifulSoup(sbin_r.text,"lxml")
    sbin_price=sbin_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return sbin_price

def canbkparsePrice():
    canbk_r=requests.get('https://in.finance.yahoo.com/quote/CANBK.NS/')
    canbk_soup=bs4.BeautifulSoup(canbk_r.text,"lxml")
    canbk_price=canbk_soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}) 
    [0].find('span').text
    return canbk_price

while True:

    wb = xw.Book('fetchlivedata.xlsx')
    sht1 = wb.sheets['Sheet1']
    sht1.range('B2').value = str(bajparsePrice())
    sht1.range('B3').value = str(infyparsePrice())
    sht1.range('B4').value = str(relparsePrice())
    sht1.range('B5').value = str(sbinparsePrice())
    sht1.range('B6').value = str(canbkparsePrice())

Tags: textimportfindrequestspriceyahoorelfinance
1条回答
网友
1楼 · 发布于 2024-10-03 21:29:35

Joblib是一个很好的工具,非常容易用于并行for循环

示例(来自其网站):

>>> from joblib import Parallel, delayed
>>> from math import sqrt
>>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

链接: https://joblib.readthedocs.io/en/latest/

相关问题 更多 >