ASYNCIO循环中ASYNCIO循环

问题描述 投票:2回答:1

我刚开始使用ASYNCIO,我想用它来分析一个网站。

我试图解析该网站的6段(self.signals),每个部分有与他们的表页N多,所以基本上我想异步调用哪个部分的循环,异步在每个部分的页面。这是我到目前为止所。

class FinViz():
    def __init__(self):
        self.url = 'https://finviz.com/screener.ashx?v=160&s='

        self.signals = {
            'Earnings_Before' : 'n_earningsbefore',
            'Earnings_After' : 'n_earningsafter',
            'Most_Active' : 'ta_mostactive',
            'Top_Gainers' : 'ta_topgainers',
            'Most_Volatile' : 'ta_mostvolatile',
            'News' : 'n_majornews',
            'Upgrade' : 'n_upgrades',
            'Unusual_Volume' : 'ta_unusualvolume' 
        }

        self.ticks = []

    def _parseTable(self, data):
        i, signal = data
        url = self.signals[signal] if i == 0 else self.signals[signal] + '&r={}'.format(str(i * 20 + 1))
        soup = BeautifulSoup(urlopen(self.url + url, timeout = 3).read(), 'html5lib')
        table = soup.find('div', {'id' : 'screener-content'}).find('table', 
            {'width' : '100%', 'cellspacing': '1', 'cellpadding' : '3', 'border' : '0', 'bgcolor' : '#d3d3d3'})
        for row in table.findAll('tr'):
            col = row.findAll('td')[1]
            if col.find('a'):
                self.ticks.append(col.find('a').text)


    async def parseSignal(self, signal):
        try:
            soup = BeautifulSoup(urlopen(self.url + self.signals[signal], timeout = 3).read(), 'html5lib')

            tot = int(soup.find('td', {'class' : 'count-text'}).text.split()[1])

            with concurrent.futures.ThreadPoolExecutor(max_workers = 20) as executor:
                loop = asyncio.get_event_loop()
                futures = []
                for i in range(tot // 20 + (tot % 20 > 0)):
                    futures.append(loop.run_in_executor(executor, self._parseTable, (i, signal)))


                for response in await asyncio.gather(*futures):
                    pass    
        except URLError:
            pass


    async def getAll(self):
        with concurrent.futures.ThreadPoolExecutor(max_workers = 20) as executor:
            loop = asyncio.get_event_loop()
            futures = []
            for signal in self.signals:
                futures.append(await loop.run_in_executor(executor, self.parseSignal, signal))

            for response in await asyncio.gather(*futures):
                pass
        print(self.ticks)

if __name__ == '__main__':

    x = FinViz()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(x.getAll())

这确实成功地做工作,但它在某种程度上确实比如果我是做解析,而不asyncio慢。

任何提示的异步菜鸟?

编辑:添加完整的代码

python asynchronous beautifulsoup python-3.5 python-asyncio
1个回答
0
投票

记住Python有一个GIL,所以线程代码不会帮助提高性能。潜在的加快速度使用ProcessPoolExecutor但是请注意,你就导致了以下开销:

  1. 泡菜/在unpickle数据到子处理工人
  2. 泡菜/在unpickle结果发送回主过程

你能避免1.如果你在叉子上的安全环境中运行,数据存储在一个全局变量。

你也可以做的东西一样共享内存映射文件...还共享原始字符串/字节是最快的。

© www.soinside.com 2019 - 2024. All rights reserved.