有参数的循环中的Python线程模块?

2024-09-30 01:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个爬虫,它可以抓取网站上的前100个页面:

我的代码是这样的:

def extractproducts(pagenumber):
    contenturl = "http://websiteurl/page/" + str(pagenumber)

    content = BeautifulSoup(urllib2.urlopen(contenturl).read())
    print pagehtml



pagenumberlist = range(1, 101)

for pagenumber in pagenumberlist:
    extractproducts(pagenumber)

在这种情况下,如何使用线程模块,以便urllib使用多线程一次抓取X个url?在

/新手出局


Tags: 代码http网站defpage页面content爬虫
1条回答
网友
1楼 · 发布于 2024-09-30 01:34:07

很有可能,您希望使用multiprocessing。有一个Pool可以用来并行执行多个任务:

from multiprocessing import Pool

# Note: This many threads may make your system unresponsive for a while
p = Pool(100)

# First argument is the function to call,
# second argument is a list of arguments
# (the function is called on each item in the list)
p.map(extractproducts, pagenumberlist)

如果函数返回任何值,Pool.map将返回返回值列表:

^{pr2}$

相关问题 更多 >

    热门问题