2017-10-19 5 views
-1

여러 페이지가있는 웹 사이트를 구문 분석하려고합니다.파이썬 다중 처리 - 주문형 작업자 사용

페이지 수를 알지 못합니다.

 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 페이지를 처리 ​​할 수 ​​있도록 구현하는 방법을 알아낼 수 없도록 3 명의 직원 중 pool을 사용하는 방법에 대해 생각했습니다. 다음

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"}) 

답변

0

대신 multiprocessingconcurrent 패키지를 사용할 수 있습니다. 예 :

import concurrent.futures 

with concurrent.futures.ProcessPoolExecutor() as executor: 
    while next_button: 
     rows = ... 
     executor.submit(function, rows) 
     next_button = ... 

당신은 executor = ProcessPoolExecutor(max_workers=10) 근로자의 임의의 양으로 executor를 인스턴스화 할 수 있지만, 주어진하지 않을 경우, max_workers은 당신의 컴퓨터에 코어의 금액을 기본값으로 설정됩니다. Further details in the python docs.

0

Pool.map() 대신 Pool.apply_async()을 사용할 수 있습니까? Apply_async가 차단되지 않고 주 프로그램에서 더 많은 행을 처리하도록 허용합니다. 또한 메인 프로그램에 모든 데이터를 매핑 할 준비가 필요하지 않습니다. apply_async()에 하나의 청크를 매개 변수로 전달하면됩니다.