簡體   English   中英

Python線程模塊與參數循環?

[英]Python threading module in loops with parameters?

我正在嘗試創建一個對網站上的前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使用mutli線程一次可以抓取X個URL?

/ newb出來

您最有可能要使用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將返回一個返回值列表:

def f(x):
    return x + 1

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM