我正在用 Python 编写一个网络抓取应用程序。我正在抓取的网站具有 www.someurl.com/getPage?id=x 形式的 url,其中 x 是标识页面的数字。现在,我正在使用 urlretrieve
这是我的脚本的基本形式:
for i in range(1,1001):
urlretrieve('http://someurl.com/getPage?id='+str(i) , str(i)+".html)
现在,我的问题 - 是否可以同时下载页面?因为,我在这里阻止了脚本并等待页面下载。我可以要求 Python 打开多个到服务器的连接吗?
请您参考如下方法:
在 Python 2 中同时获取一些谷歌搜索:
from multiprocessing.pool import ThreadPool
from urllib import urlretrieve
def loadpage(x):
urlretrieve('http://google.com/search?q={}'.format(x), '{}.html'.format(x))
p = ThreadPool(10) # the max number of webpages to get at once
p.map(loadpage, range(50))
您可以轻松地使用 Pool 而不是 ThreadPool。这将使它在多个进程/CPU 内核上运行。但由于这是 IO 绑定(bind),我认为线程提供的并发性就足够了。
