我想分析一个包含多个页面的网站。Python多处理 - 按需使用工作人员
我不知道页数。 这是原来的代码:
next_button=soup.find_all('a',{'class':"btn-page_nav right"})
while next_button:
link=next_button[0]['href']
resp=requests.get('webpage+link)
soup=BeautifulSoup(resp.content)
table=soup.find('table',{'class':'js-searchresults'})
body=table.find('tbody')
rows=body.find_all('tr')
function(rows)
next_button=soup.find_all('a',{'class':"btn-page_nav right"})
它工作正常,function(rows)
是解析每个页面的一部分的功能。
我想要做的是使用multiprocessing
解析这些页面。我想过使用3名工人的pool
,以便我可以一次处理3页,但我无法弄清楚如何实施它。
一种解决方案是这样的:
rows_list=[]
next_button=soup.find_all('a',{'class':"btn-page_nav right"})
while next_button:
link=next_button[0]['href']
resp=requests.get('webpage+link)
soup=BeautifulSoup(resp.content)
table=soup.find('table',{'class':'js-searchresults'})
body=table.find('tbody')
rows=body.find_all('tr')
rows_list.append(rows)
next_button=soup.find_all('a',{'class':"btn-page_nav right"})
等待程序遍历所有页面,然后:
pool=multiprocessing.Pool(processes=4)
pool.map(function,rows_list)
但我不认为这会提高性能太多了,我希望主进程遍历页面,一旦打开页面,就将其发送给工作人员。 这个怎么办?一个虚拟的例子:
pool=multiprocessing.Pool(processes=4)
next_button=soup.find_all('a',{'class':"btn-page_nav right"})
while next_button:
link=next_button[0]['href']
resp=requests.get('webpage+link)
soup=BeautifulSoup(resp.content)
table=soup.find('table',{'class':'js-searchresults'})
body=table.find('tbody')
rows=body.find_all('tr')
**pool.send_to_idle_worker(rows)**
next_button=soup.find_all('a',{'class':"btn-page_nav right"})