I want to write a spider program to download web pages using gevent in python3. Here is my code:
import gevent
import gevent.pool
import gevent.monkey
import urllib.request
gevent.monkey.patch_all()
def download(url):
return urllib.request.urlopen(url).read(10)
urls = ['http://www.google.com'] * 100
jobs = [gevent.spawn(download, url) for url in urls]
gevent.joinall(jobs)
But when I run it, there is an error:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/gevent/greenlet.py", line 340, in run
result = self._run(*self.args, **self.kwargs)
File "e.py", line 8, in download
return urllib.request.urlopen(url).read(10)
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
return opener.open(url, data, timeout)
......
return greenlet.switch(self)
gevent.hub.LoopExit: This operation would block forever
<Greenlet at 0x7f4b33d2fdf0: download('http://www.google.com')> failed with LoopExit
......
It seems that the urllib.request blocks, so the program can not work. How to solve it?