Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带参数的循环中的Python线程模块?_Python_Multithreading_Urllib2 - Fatal编程技术网

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

带参数的循环中的Python线程模块?,python,multithreading,urllib2,Python,Multithreading,Urllib2,我正在尝试创建一个爬网程序,它可以爬网网站上的前100个页面: 我的代码是这样的: def extractproducts(pagenumber): contenturl = "http://websiteurl/page/" + str(pagenumber) content = BeautifulSoup(urllib2.urlopen(contenturl).read()) print pagehtml pagenumberlist = range(1, 1

我正在尝试创建一个爬网程序,它可以爬网网站上的前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


/新手退出

最有可能的情况是,您希望使用。有一个池可用于并行执行多项任务:

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将返回返回值列表:

def f(x):
    return x + 1

results = Pool().map(f, [1, 4, 5])
print(results) # [2, 5, 6]

最有可能的情况是,您希望使用。有一个池可用于并行执行多项任务:

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将返回返回值列表:

def f(x):
    return x + 1

results = Pool().map(f, [1, 4, 5])
print(results) # [2, 5, 6]

哇,这太快了,正是我想要的。您的internet points很好,先生。@user1271067如果这对您有帮助,请单击我的答案旁边的复选标记,将其标记为已接受,如果您愿意,请单击向上箭头。目前没有足够的代表给您投赞成票。:/顺便说一句,多处理似乎并没有使urllib获取页面更快,似乎仍然是一次获取一个页面。可能只是因为我的连接速度慢,我会租一台网络更快的服务器,看看是否更好。但指导我进行多处理已经足够好了,我相信我会在阅读官方文档和其他有关StackOverflow的问题后找到答案。@user1271067-您可以在发出请求之前在函数中打印一些内容,这样您至少可以看到它们是并行发生的。我希望这至少快一点。哇,这太快了,正是我想要的。您的internet points很好,先生。@user1271067如果这对您有帮助,请单击我的答案旁边的复选标记,将其标记为已接受,如果您愿意,请单击向上箭头。目前没有足够的代表给您投赞成票。:/顺便说一句,多处理似乎并没有使urllib获取页面更快,似乎仍然是一次获取一个页面。可能只是因为我的连接速度慢,我会租一台网络更快的服务器,看看是否更好。但指导我进行多处理已经足够好了,我相信我会在阅读官方文档和其他有关StackOverflow的问题后找到答案。@user1271067-您可以在发出请求之前在函数中打印一些内容,这样您至少可以看到它们是并行发生的。我希望这至少会快一点。