在用python爬取数据时,单进程里开启多线程抓取,毕竟IO密集我就没搞多进程了。
代码如下
def get_downloads_url_list(self,pageNum):
FilePath='C:/RMDZY/h'+str(pageNum)
os.chdir(FilePath)
with open(FilePath+'/m3u8.txt', 'r') as f:
m3u8_txt = f.read()
download_ts_list = re.findall(r'ppvod' + r'\d{7}' + r'.ts', m3u8_txt)
download_url_list = [url + str(pageNum) + '/1000kb/hls/' + download_ts_list[i] for i in
range(len(download_ts_list))]
max_length=len(download_url_list)
dat_list=['ts'+str(i)+'.ts' for i in range(max_length)]
dat_str='+'.join(dat_list)
ts_command='copy /b '+dat_str+' new.ts'
with open('ts.bat','w') as f:
f.write(ts_command)
return download_url_list
def download_by_m3u8(self,i,pageNum):
download_list=self.get_downloads_url_list(pageNum)
ts_file = requests.get(download_list[i], verify=False)
with open('ts'+str(i)+'.ts','ab') as f:
f.write(ts_file.content)![图片描述][1]
def download_threading(self,pageNum):
download_list=self.get_downloads_url_list(pageNum)
thread_list=[]
for i in range(len(download_list)):
thread = threading.Thread(target=self.download_by_m3u8, args=[i,pageNum])
thread_list.append(thread)
thread.start()
for thread in thread_list:
thread.join()
但是只要一个线程的requests没有返回值,线程就会一直等待,也不会写入,所以会出现,主进程一直没阻塞的问题。
如图
请问怎么处理,比如,给requests.get设置一个timeout,但是超过之后怎么处理啊,我设置了timeout之后,好像线程直接被kill了,可以继续下载下一个目标,但是,这个没下载的我这么记录啊,能不能捕获这个异常然后重连啊。主要还是写法,不太会。生疏啊