刚开始研究多线程,看了很多视频跟文章,但还是概念混淆,所以过来论坛求助。
1、
对于爬虫而言,for 循环多线程抓取 N 个页面,然后获取内容到 MongoDB 数据库,错误链接写入 error.txt,是线程安全的吗?如果不安全,我通过在类里面的采集入库跟写入文件加锁,是不是可以解决?我之前没加锁,抓了 36W 条数据,感觉没发现有什么问题。
入库部分如下:
# 启动抓取函数 def run(self): try: rst_json = self.claw_detail() if rst_json != None: gLock.acquire() result = table_lines.insert_one(rst_json) gLock.release() else: result = 'null' except: with open(file_path + "/error.txt", 'a+') as f1: f1.write(self.hotelid) f1.write('\n') f1.flush() result = 'error' time.sleep(5) finally: time.sleep(1) return result 2、
多层 for 循环嵌套的时候,这么用多线程可以吗? t.join()这么用没有问题吧? t.setDaemon(True)需要设置吗?
main 函数
def main(): for dateTuple in dateList:
threads = [] for i in id_lines.find(): hotelId = i.get('hotelId') threads.append(hotelId) for hotelid in threads: t = ClawData(hotelid,headersCookie) #t.setDaemon(True) t.start() for hotelid in threads: t.join() time.sleep(3) 非常感谢!
