1.每次从queue队列中拿出了,一定要从task_done(),让队列数减去1
import requests
from lxml import etree
from queue import Queue
import threading
import time
class QiuBai:
def __init__(self):
self.temp_url = "http://www.qiushibaike.com/8hr/page/{}"
self.headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
}
self.url_queue = Queue()
self.html_queue = Queue()
self.content_list_queue = Queue()
def get_url_list(self):
for i in range(1, 14):
self.url_queue.put(self.temp_url.format(i))
def parse_url(self):
while True:
url = self.url_queue.get()
response = requests.get(url, headers=self.headers)
if response.status_code != 200:
self.url_queue.put(url)
else:
self.html_queue.put(response.content.decode())
self.url_queue.task_done()
def get_content_list(self):
while True:
html_str = self.html_queue.get()
html = etree.HTML(html_str)
div_list = html.xpath("//div[@id='content-left']/div")
content_list = []
for div in div_list:
item = {}
item["user_name"] = div.xpath(".//h2/text()")[0].strip()
item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
content_list.append(item)
self.content_list_queue.put(content_list)
self.html_queue.task_done()
def save_content_list(self):
while True:
content_list = self.content_list_queue.get()
for content in content_list:
pass
self.content_list_queue.task_done()
def run(self):
thread_list = []
t_url = threading.Thread(target=self.get_url_list)
thread_list.append(t_url)
for i in range(3):
t_parse = threading.Thread(target=self.parse_url)
thread_list.append(t_parse)
t_content = threading.Thread(target=self.get_content_list)
thread_list.append(t_content)
t_save = threading.Thread(target=self.save_content_list)
thread_list.append(t_save)
for t in thread_list:
t.setDaemon(True)
t.start()
for q in [self.url_queue, self.html_queue, self.content_list_queue]:
q.join()
if __name__ == '__main__':
t1 = time.time()
qiubai = QiuBai()
qiubai.run()
print("total cost:", time.time() - t1)