1- # 豆瓣电影Top250 爬虫
2-
3- 标签(空格分隔): python
4-
1+ ---
2+ title : 豆瓣电影Top250 爬虫
3+ date : 2016-10-18 20:19:35
4+ tags : Python
55---
66
7- ## 爬取豆瓣电影top250。
7+ ### 爬取豆瓣电影top250。
88
9- ## 1. 单线程版
9+ #### 1. 单线程版
1010``` python
1111# -*- coding: utf-8 -*-
1212
@@ -52,7 +52,7 @@ Out: CPU times: user 1.11 s, sys: 8 ms, total: 1.12 s
5252Wall time: 3.58 s
5353```
5454
55- ## 2. 多线程版
55+ #### 2. 多线程版
5656``` python
5757# -*- coding: utf-8 -*-
5858
@@ -99,7 +99,7 @@ if __name__ == '__main__':
9999Out: CPU times: user 1.16 s, sys: 172 ms, total: 1.33 s
100100Wall time: 1.28 s
101101```
102- ### 使用线程池
102+ #### 使用线程池
103103线程的创建和销毁是一个比较重的开销。所以,使用线程池,重用线程池中的线程!
104104
105105``` python
@@ -115,7 +115,7 @@ Out: CPU times: user 1.23 s, sys: 152 ms, total: 1.38 s
115115Wall time: 1.29 s
116116```
117117再加上一个异步的吧
118- ## 3. 异步版
118+ #### 3. 异步版
119119此版本使用的是异步库` asyncio ` 和对其进行深度封装的库` aiohttp ` 。
120120``` python
121121# coding=utf-8
@@ -159,10 +159,60 @@ if __name__ == '__main__':
159159Out: CPU times: user 984 ms, sys: 28 ms, total: 1.01 s
160160Wall time: 1.67 s
161161```
162+ #### 4. 使用下 Gevent 看看效果如何。
163+ ``` python
164+ # coding=utf-8
165+
166+ import re
167+ import requests
168+ import gevent
169+ from gevent.pool import Pool
170+ from bs4 import BeautifulSoup as bs
171+
172+
173+ def fetch (url ):
174+ s = requests.Session()
175+ s.headers.update({" user-agent" : user_agent})
176+ return s.get(url)
177+
178+
179+ def title_get (url ):
180+ try :
181+ result = fetch(url)
182+ except requests.exceptions.RequestException:
183+ return False
184+ html = bs(result.text, ' lxml' )
185+ title_list = html.select(' div.pic > a > img' )
186+ '''
187+ title_list中的元素格式如下 e.g:
188+ <img alt="这个杀手不太冷" class="" src="https://img3.doubanio.com
189+ /view/movie_poster_cover/ipst/public/p511118051.jpg"/
190+ '''
191+ try :
192+ title = [re.findall(r ' alt="( . *? ) "' , str (title))[0 ]
193+ for title in title_list]
194+ except IndexError :
195+ pass
196+ return title
197+
198+
199+ if __name__ == ' __main__' :
200+ user_agent = ' Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
201+ (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
202+ url = ' https://movie.douban.com/top250?start={} &filter='
203+ urls = [url.format(page) for page in range (0 , 250 , 25 )]
204+ # %time gevent.joinall([gevent.spawn(title_get, url) for url in urls])
205+ pool = Pool(1000 )
206+ % time pool.map(title_get, urls)
207+
208+ CPU times: user 960 ms, sys: 32 ms, total: 992 ms
209+ Wall time: 3.67 s
210+ ```
162211## 总结
163212
164213** 以上测试时间基于笔者电脑的配置和网络情况, 因人而异!**
165214
1662151 . 单线程和多线程的对比,可以看到,使用多线程后速度提升了3倍。
1672162 . 使用线程池后,在限制线程数的状态下,依然有着不错的速度!
168- 3 . 使用异步虽然在这里并没有多大的优势相对于多线程来说,但是当请求量很大时,就能显示出异步的强大了。在这里就不做过多赘述了!
217+ 3 . 使用异步虽然在这里并没有多大的优势相对于多线程来说,但是当请求量很大时,就能显示出异步的强大了。在这里就不做过多赘述了!
218+ 4 . 我也不明白为啥使用 ` gevent ` 后的速度尽然是这个这样子, 晕!!!
0 commit comments