多进程的爬虫之糗事百科(三)
2018-12-05 本文已影响12人
buaishengqi
采用多进程实现糗事百科的爬取
from multiprocessing import Process
p1 = Process(target=func,args=(,))
p1.daemon = True #设置为守护进程
p1.start() #此时线程才会启动
3.2 多进程中队列的使用
多进程中使用普通的队列模块会发生阻塞,对应的需要使用multiprocessing提供的JoinableQueue模块,其使用过程和在线程中使用的queue方法相同
"""
@author:Rudy
@time : 12月5日
@message:多进程爬取糗事百科热门上的段子用户昵称
"""
from multiprocessing import Process
import requests
from lxml import etree
from multiprocessing import JoinableQueue as Queue
import time
class QiuBai():
def __init__(self):
self.temp_url = "https://www.qiushibaike.com/8hr/page{}"
self.headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"}
self.url_queue = Queue()
self.html_queue = Queue()
self.content_list_queue = Queue()
self.proxies = {"http":"http://58.242.136.18:808"} # 可以在此添加IP代理
def get_url_list(self):
for i in range(1,14):
self.url_queue.put(self.temp_url.format(i))
def parse_url(self): # 不在接收参数,而是直接从url列表中取
while True:
url = self.url_queue.get()
response = requests.get(url, headers=self.headers,proxies=self.proxies)
print(response)
if response.status_code != 200:
self.url_queue.put(url)
# return response.content.decode() 取完之后不在返回
else:
self.html_queue.put(response.content.decode())
self.url_queue.task_done() # 让队列的计数减1
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()")
item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")] # 列表推导式
content_list.append(item)
# return content_list
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:
# print(content)
pass
self.content_list_queue.task_done()
def run(self): # 实现主要的逻辑
thread_list = []
# 1 准备URL列表
t_url = Process(target= self.get_url_list)
thread_list.append(t_url)
# 2 遍历发送请求,获取响应
for i in range(4): # 启动3个进程,如果感觉爬取速度还很慢,可以加大进程
t_parse = Process(target=self.parse_url)
thread_list.append(t_parse)
# 3 提取数据
t_content = Process(target=self.get_content_list)
thread_list.append(t_content)
# 4 保存
t_save = Process(target=self.save_content_list)
thread_list.append(t_save)
for process in thread_list: # 设置子进程守护线程
process.daemon = True
process.start()
for q in [self.url_queue,self.content_list_queue,self.html_queue]:
q.join() # 让主进程阻塞,等待队列计数为0
if __name__ == '__main__':
t1 = time.time()
qiubai = QiuBai()
qiubai.run()
print("total cost:",time.time()-t1)