上一篇聊的爬整站的例子上,爬虫的动力主要是依靠一个同步的循环体,很明显,就行进速度来说,它太慢了。雪上加霜的是在我这个地区,访问示例中的目标网站的速度还很不理想。因此我想把他改进一下。
改进思路
通过分析,发现影响速度的主要是两个方面:
- cache 队列太长,每次只能消化一个元素
- 网络访问速度慢
网络访问速度可以通过加代理来解决,不过这个不是我们这次要聊的主题。我们着重分析一下如何提升cache队列的消化速度。如图所示,之前的例子中每次只能消化一个元素,而且还是得在消化完之后才论到下一个。我希望的是——队列中只要一有元素,马上开始处理。这个场景中,我不需要等待它为我返回处理结果,因为它自会把处理结果put进相应的队列中。
先看看伪码的实现
def 爬取(url):
html = 访问(url)
for td in html:
if 在<td>中找到了<span class="octicon octicon-file-directory">:
cache.入队(td.url)
elif 在<td>中找到了<span class="octicon octicon-file-text">:
处理爬取成果
while:
url = 首元素出队
if 超时返回:
已经爬完整站,退出循环
启动新线程(爬取(url))
完整代码
from bs4 import BeautifulSoup
import requests
import threading
import time
class LQueue:
def __init__(self):
self._queue = []
self.mutex = threading.Lock()
self.condition = threading.Condition(self.mutex)
def put(self, item):
with self.condition:
self._queue.append(item)
self.condition.notify()
def get_nowait(self):
if not self.empty():
return self._queue.pop(0)
else:
raise IndexError('Empty Queue')
def get(self, timeout=60):
with self.condition:
endtime = time.time() + timeout
while True:
if not self.empty():
return self._queue.pop(0)
else:
remaining = endtime - time.time()
if remaining <= 0.0:
return None
self.condition.wait(remaining)
def has(self, item):
if item in self._queue:
return True
else:
return False
def empty(self):
if self._queue.__len__() == 0:
return True
else:
return False
def find_links(url, queue):
print('Accessing:{}'.format(url))
headers = {
'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'
}
try:
html = requests.get(url, headers=headers, timeout=30)
html.raise_for_status
html.encoding = html.apparent_encoding
except:
return
soup = BeautifulSoup(html.text, "html.parser")
tds = soup.find('tbody').find_all('td', class_='name four wide')
for td in tds:
if td.find('span', class_='octicon octicon-file-directory') is not None:
# directory enqueue 'cache'
href = 'https://opendev.org' + td.find('a')['href']
if not queue.has(href):
queue.put(href)
elif td.find('span', class_='octicon octicon-file-text') is not None:
href = 'https://opendev.org' + td.find('a')['href']
# 处理爬取成果
cache = LQueue()
link = 'https://opendev.org/openstack/neutron'
cache.put(link)
while True:
url = cache.get(35)
if url is None:
break
threading.Thread(target=find_links, args=(url, cache)).start()
这时候你可以跑一下,体会那种充分利用计算机资源的感觉。不过在这段代码里,我没有写对爬取成果处理的部分。因为我想介绍一个有意思的东西——任务队列。在这个场景中,它跟多线程的作用差不多,但它真正的意义在于能帮我把任务分发到其他机器上去执行,类似的好处还有使用“订阅-发布”让多台机器帮你一起干等等。至于分发什么任务,这就随心所欲了。比如把所有URL成果放进数据库里,再设计一个定时任务,让它每过一会帮你做一次去重操作。
我用的是RQ(RedisQueue),一个很轻量级的 python 任务队列库,RQ 的工作依赖于Redis,并且需要 Redis版本 >= 3.0.0.。我已经安装过了,直接运行。
$ redis-server
注意:由于我是本地运行、使用,因此Redis侦听localhost:6379,并且我连接它的时候也不需要安全验证。如果你是在不同的机器上,需要合理的修改配置文件。
接着安装rq库
$ pip3 install rq
增加实现 rq 的代码
...
import rq
from redis import Redis
class LQueue:
...
def find_links(url, queue, task_queue):
...
elif td.find('span', class_='octicon octicon-file-text') is not None:
# 把爬取成果发送到任务队列,让 'process_result' 去处理
href = 'https://opendev.org' + td.find('a')['href']
task_queue.enqueue('tasks.process_result', href)
...
cache.put(link)
# 创建任务队列对象,绑定到名叫 'task1' 的worker上
task_queue1 = rq.Queue('task1', connection=Redis.from_url('redis://'))
while True:
url = cache.get(35)
if url is None:
break
threading.Thread(target=find_links, args=(url, cache, task_queue1)).start()
任务队列里有个worker
的概念,当我使用obj.enqueue()
把任务送进队列之后,worker
正这个任务的执行者。即然是交给人家任务,那就得告诉人家怎么干,如果需要加工原材料,那原材料也得一并提供。例如我把一张原始表单发给助理,告诉她明天下班之前按预定模板整理成报表并邮件发送给张三抄给我。助理就是worker。在task_queue.enqueue('tasks.process_result', href)
中,'tasks.process_result'
是任务描述,href
是原始表单。多个worker可以同时绑定到一个队列上,就好比我有多个助理,他们同时帮我干一件事。每个worker也可以分别绑到不同的队列上,就像我把不同的任务交给不同的助理。
在工作目录下创建文件tasks.py
,并添加任务处理代码。我尽量言简意赅,保持页面清爽,就直接print了,想像留给你。
def process_result(href):
print(href)
接着开启一个新的终端窗口,进入到工作目录,启动一个worker
rqworker task1
再试着跑一下,看看worker的控制台是不是像我的一样输出的url内容。
限制并发访问数量
如果一直停留在访问初始连接的字样上,很有可能是刚刚开启的线程数量太大,导致目标站服务器让你“冷静一会”。这时候尝试用浏览器再访问一下初始URL,如果一直连接不成功,就可以确认结果了。
说实话我是非常喜欢那种简单粗爆直接硬来的畅快感,像不堵车的五环一脚油到底。可目标站显然承受不了这种过量的连接。工具在给我们带来便利的同时,它也产生了一定的危害。说到底,关键在于利刃作什么用。切记要在合理合法的范围内收集信息。
像上面的例子实际来说是不可取的,也行不通。我准备再次优化一下,限制它并发访问的数量。
还是先来看看伪码的实现
def 爬取(url):
html = 访问(url)
for td in html:
if 在<td>中找到了<span class="octicon octicon-file-directory">:
cache.入队(td.url)
elif 在<td>中找到了<span class="octicon octicon-file-text">:
处理爬取成果
唤醒因数量过载而被阻塞的线程
while 队列不为空:
url = 首元素出队
if url is None:
已经爬完整站,退出循环
if 计数器过载
等待运行中的线程执行完毕后唤醒我
计数器 ++
多线程爬取(url)
计数器 --
增加限制和唤醒线程的代码
class LQueue:
...
def find_links(url, queue, task_queue, condition):
print('Accessing:{}'.format(url))
headers = {
'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'
}
try:
html = requests.get(url, headers=headers, timeout=30)
html.raise_for_status
html.encoding = html.apparent_encoding
except:
with condition:
# 异常情况下的唤醒
condition.notify()
return
soup = BeautifulSoup(html.text, "html.parser")
tds = soup.find('tbody').find_all('td', class_='name four wide')
for td in tds:
if td.find('span', class_='octicon octicon-file-directory') is not None:
# directory enqueue 'cache'
href = 'https://opendev.org' + td.find('a')['href']
if not queue.has(href):
queue.put(href)
elif td.find('span', class_='octicon octicon-file-text') is not None:
# send to task queue
href = 'https://opendev.org' + td.find('a')['href']
task_queue.enqueue('tasks.process_result', href)
with condition:
# 正常执行完毕后的唤醒
condition.notify()
cache = LQueue()
link = 'https://opendev.org/openstack/neutron'
cache.put(link)
task_queue1 = rq.Queue('task1', connection=Redis.from_url('redis://'))
condition = threading.Condition(threading.Lock())
# 最多同时开启线程
counter = 5
while True:
url = cache.get(35)
if url is None:
break
if counter <= 0:
with condition:
condition.wait()
counter = counter + 1
threading.Thread(target=find_links, args=(url, cache, task_queue1, condition)).start()
counter = counter - 1