gevent异步爬虫

本文首发于知乎
之前我们讲过基于asycnio的异步爬虫实现,不过代码过于复杂,本文我们使用gevent模块实现异步爬虫。

本文分为如下部分

  • 用gevent实现异步爬虫
  • grequests模块

用gevent实现异步爬虫

因为使用非常简单,就直接上代码了

import gevent
from gevent import monkey
import requests
from bs4 import BeautifulSoup
monkey.patch_all() # 对所有io操作打上补丁,固定加这一句
def get_title(i):
url = 'https://movie.douban.com/top250?start={}&filter='.format(i*25)
text = requests.get(url).content
soup = BeautifulSoup(text, 'html.parser')
lis = soup.find('ol', class_='grid_view').find_all('li')
for li in lis:
title = li.find('span', class_="title").text
print(title)
gevent.joinall([gevent.spawn(get_title, i) for i in range(10)])
复制代码

gevent本质上是开启了多个微线程,下面我们用threading模块来检验一下

import gevent
from gevent import monkey
import requests
from bs4 import BeautifulSoup
import threading
monkey.patch_all()
def get_title(i):
print(threading.current_thread().name) # 打印出当前线程名称
url = 'https://movie.douban.com/top250?start={}&filter='.format(i*25)
text = requests.get(url).content
soup = BeautifulSoup(text, 'html.parser')
lis = soup.find('ol', class_='grid_view').find_all('li')
for li in lis:
title = li.find('span', class_="title").text
print(title)
gevent.joinall([gevent.spawn(get_title, i) for i in range(10)])
复制代码

运行结果首先打印出了下面内容

DummyThread-1
DummyThread-2
DummyThread-3
DummyThread-4
DummyThread-5
DummyThread-6
DummyThread-7
DummyThread-8
DummyThread-9
DummyThread-10
复制代码

表示这里其实开了10个微线程同时运行。

其实我们也可以控制用一个线程来完成,只需要这样改

monkey.patch_all()
改成
monkey.patch_all(thread=False)
复制代码

grequests模块

requests库的作者将requests和gevent融合产生了grequests模块,专门用于异步网络请求,使用如下

import grequests
from bs4 import BeautifulSoup
def get_title(rep):
soup = BeautifulSoup(rep.text, 'html.parser')
lis = soup.find('ol', class_='grid_view').find_all('li')
for li in lis:
title = li.find('span', class_="title").text
print(title)
reps = (grequests.get('https://movie.douban.com/top250?start={}&filter='.format(i*25)) for i in range(10))
for rep in grequests.map(reps):
get_title(rep)
复制代码

欢迎关注我的知乎专栏

专栏主页:python编程

专栏目录:目录

版本说明:软件及包版本说明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值