请问这个 asyncio 异步访问页面怎么写可以更加快?

2020-11-24 21:41:51 +08:00
 yagamil

代码如下: 先在主页获取子页面,大概 64 个,然后并发访问子页面, 总用时大概 36s,感觉还是有点慢。


URL_MAP = {'home_page': 'https://xxx/stocks/industry', 'base': 'https://xxx.com'}


class App(BaseService):

    def __init__(self):
        super(App, self).__init__()


    async def home_page(self):
        start = time.time()
        async with aiohttp.ClientSession() as session:

            async with session.get(url=URL_MAP['home_page'], headers=headers) as response:
                    html = await response.text()  # 这个阻塞
                    resp = Selector(text=html)
                    industries = resp.xpath('//ul[@class="list-unstyled"]/a')
                    task_list =[]
                    for industry in industries:
                        json_data = {}
                        industry_url = industry.xpath('.//@href').extract_first()
                        industry_name = industry.xpath('.//li/text()').extract_first()
                        json_data['industry_url'] = industry_url
                        json_data['industry_name'] = industry_name

                        task = asyncio.ensure_future(self.detail_list(session, industry_url, json_data))
                        task_list.append(task)

                    await asyncio.gather(*task_list)
                    end = time.time()

                    print(f'time used {end-start}')

    async def detail_list(self, session, url, json_data):

        async with session.get(URL_MAP['base']+url, headers=headers) as response:
            response = await response.text()
            self.parse_detail(response, json_data)

    def parse_detail(self, html, json_data=None):
        resp = Selector(text=html)
        # info = resp.xpath('//div[@id="v_desc"]/div[@class="info open"]/text()').extract_first()
        title =resp.xpath('//title/text()').extract_first()
        print(title)


app = Holdle()
loop = asyncio.get_event_loop()
loop.run_until_complete(app.home_page())
1836 次点击
所在节点    Python
7 条回复
ClericPy
2020-11-24 21:59:47 +08:00
把每个请求用时打出来挨个看看, 找不到再考虑代码层面优化(比如 pysnooper), 看起来没有异常同步代码阻塞协程的地方, 该复用 Session 的地方也复用了, 所以感觉主要网速问题上...

如果同步代码还想稍微提速, 可以试试 selectolax, 测过它和 lxml 的 cssselector 比较, 快了大约一倍, 不过没做 xpath 的比较, 用惯了 css 的语义以后很少碰 xpath 了
yagamil
2020-11-24 22:53:17 +08:00
@ClericPy 嗯,应该是网速问题,转为同步后,用时为 131s,是异步的 4 倍多。
inframe
2020-11-24 23:01:38 +08:00
httpx 也可以,比 aiohttp 要更接近 requests 的用法
ClericPy
2020-11-24 23:05:06 +08:00
@yagamil 主流 HTTP Client 里面, 已经基本没有比 aiohttp 快的库了...
Sparetire
2020-11-25 08:37:56 +08:00
害,爬那么快做啥呢,给人发现了还得改代码。。当然要是不设防的站当我没说
讲道理都异步并发了剩下能较大提升的点就网络带宽和页面解析了吧
lithbitren
2020-11-25 13:48:42 +08:00
aiohttp 的 io 已经足够快了,写起来比 requests 繁琐一点点不过可以自己封起来,单机访问云服务器可以达到每秒 9000 左右的入包,剩下的瓶颈应该基本就是解析和带宽的问题了。
chaogg
2020-11-25 14:12:31 +08:00
把解析放到单独的进程中试试

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/728863

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX