
代码如下: 先在主页获取子页面,大概 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()) 1 ClericPy 2020-11-24 21:59:47 +08:00 把每个请求用时打出来挨个看看, 找不到再考虑代码层面优化(比如 pysnooper), 看起来没有异常同步代码阻塞协程的地方, 该复用 Session 的地方也复用了, 所以感觉主要网速问题上... 如果同步代码还想稍微提速, 可以试试 selectolax, 测过它和 lxml 的 cssselector 比较, 快了大约一倍, 不过没做 xpath 的比较, 用惯了 css 的语义以后很少碰 xpath 了 |
3 inframe 2020-11-24 23:01:38 +08:00 httpx 也可以,比 aiohttp 要更接近 requests 的用法 |
5 Sparetire 2020-11-25 08:37:56 +08:00 via Android 害,爬那么快做啥呢,给人发现了还得改代码。。当然要是不设防的站当我没说 讲道理都异步并发了剩下能较大提升的点就网络带宽和页面解析了吧 |
6 lithbitren 2020-11-25 13:48:42 +08:00 aiohttp 的 io 已经足够快了,写起来比 requests 繁琐一点点不过可以自己封起来,单机访问云服务器可以达到每秒 9000 左右的入包,剩下的瓶颈应该基本就是解析和带宽的问题了。 |
7 chaogg 2020-11-25 14:12:31 +08:00 把解析放到单独的进程中试试 |