我想讓我的實際爬蟲多線程。
當我設置多線程時,該函數的幾個實例將被啓動。避免重複結果多線程Python
例:
如果我的功能我用print range(5)
,我將有1,1,2,2,3,3,4,4,5,5
如果我有2個線程。
如何在Multithread中得到結果1,2,3,4,5
?
我實際的代碼是履帶,你可以看到下:
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)
我怎麼能調用多線程trade_spider()
不重複的鏈接?
您是否嘗試過使用[shared_ multiprocessing.Value'](https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes)? –
還沒有,我會嘗試 – Pixel
@DavidCullen請你給我一個例子,我不明白共享多處理在文檔中是如何工作的。謝謝 – Pixel