2016-08-16 12 views
1


私は実際のクローラをマルチスレッドにしようとしています。
マルチスレッドを設定すると、関数のいくつかのインスタンスが開始されます。重複する結果を避けるマルチスレッドPython

Exemple:

私の機能は、私がprint range(5)を使用して、私は2スレッドを持っている場合、私は1,1,2,2,3,3,4,4,5,5を持つことになります。

1,2,3,4,5をマルチスレッドで使用するにはどうすればよいですか?私は、重複リンクなしマルチスレッドでtrade_spider()呼び出すことができますどのように

import requests 
from bs4 import BeautifulSoup 

def trade_spider(max_pages): 
    page = 1 
    while page <= max_pages: 
     url = "http://stackoverflow.com/questions?page=" + str(page) 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text, "html.parser") 
     for link in soup.findAll('a', {'class': 'question-hyperlink'}): 
      href = link.get('href') 
      title = link.string 
      print(title) 
      get_single_item_data("http://stackoverflow.com/" + href) 
     page += 1 

def get_single_item_data(item_url): 
    source_code = requests.get(item_url) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text, "html.parser") 
    res = soup.find('span', {'class': 'vote-count-post '}) 
    print("UpVote : " + res.string) 

trade_spider(1) 

:あなたが下に見ることができるよう

私の実際のコードは、クローラのですか?

+0

[共有 'マルチプロセッシング。値]](https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes)を試したことがありますか? –

+0

まだ、私は試してみます – Pixel

+0

@DavidCullenあなたは私に例を教えてください、私は共有マルチプロセッシングがどのようにドキュメント内で動作するかはわかりません。ありがとうございます – Pixel

答えて

1

ページ番号をtrade_spider関数の引数にする必要があります。

各プロセスの関数を異なるページ番号で呼び出して、各スレッドが一意のページを取得するようにします。例えば

import multiprocessing 

def trade_spider(page): 
    url = "http://stackoverflow.com/questions?page=%s" % (page,) 
    source_code = requests.get(url) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text, "html.parser") 
    for link in soup.findAll('a', {'class': 'question-hyperlink'}): 
     href = link.get('href') 
     title = link.string 
     print(title) 
     get_single_item_data("http://stackoverflow.com/" + href) 

# Pool of 10 processes 
max_pages = 100 
num_pages = range(1, max_pages) 
pool = multiprocessing.Pool(10) 
# Run and wait for completion. 
# pool.map returns results from the trade_spider 
# function call but that returns nothing 
# so ignoring it 
pool.map(trade_spider, num_pages) 
+0

私は例をしてもらえますか? – Pixel

+1

例を更新 – danny

1

このお試しください:

def trade_spider(max_pages, page) 

from multiprocessing import Process, Value 
import time 

max_pages = 100 
shared_page = Value('i', 1) 
arg_list = (max_pages, shared_page) 
process_list = list() 
for x in range(2): 
    spider_process = Process(target=trade_spider, args=arg_list) 
    spider_process.daemon = True 
    spider_process.start() 
    process_list.append(spider_process) 
for spider_process in process_list: 
    while spider_process.is_alive(): 
     time.sleep(1.0) 
    spider_process.join() 

変更trade_spiderのパラメータリストをして

page = 1 
を削除

これにより、pageの値を共有することによってページリストを処理する2つのプロセスが作成されます。

関連する問題