异步协程编程可以在IO操作时大幅提高处理速度,在爬虫爬取信息时有大量的IO操作,正是异步协程的良好运用场景。 代码图片如下: 提取出的文件信息如下: 具体代码: importrequests importre frombs4importBeautifulSoup importasyncio importaiohttp importaiofiles importcsv asyncdefget(i): urlfhttps:www。dytt8。nethtmlgndydyzzlist23{i}。html asyncwithaiohttp。ClientSession()ass: asyncwiths。get(url)asres: res。encodinggb2312 htmlawaitres。text() respBeautifulSoup(html,html。parser) tablesresp。findall(nametable,width100,border0,cellspacing0, cellpadding0,classtbspan,stylemargintop:6px) fortableintables: atable。find(a) ulhttps:www。dytt8。neta。get(href) namea。text asyncwithaiofiles。open(move。csv,a,encodingutf8,newline)asf: wcsv。writer(f) awaitw。writerow(〔url,name,ul〕) asyncdefmain(): task〔〕 foriinrange(1,200): task。append(asyncio。createtask(get(i))) awaitasyncio。wait(task) ifnamemain: loopasyncio。geteventloop() loop。rununtilcomplete(main()) 这写这一爬虫过程中运用了:aiohttp模块异步请求网页,运用BeautiulSoup来提取所需信息,用CSV文件来存储提取出的信息,异步协程编程可在IO请求时节省大量时间,正是爬虫所需