#########################主master服务器
from redis import StrictRedis
import time
r=StrictRedis(host=‘localhost’,decode_responses=True,port=6379)
with open(‘sh1.txt’,‘r’,encoding=‘utf-8’) as f: #####读取本地数据上传到redis数据库
ls=f.readlines()
[r.hset(‘urls’,i,‘1’) for i in ls] #设置未下载状态为1
print(‘执行完毕’,r.hlen(‘urls’),len(ls))
while True:
values =r.hvals(‘urls’)
baifen=len([i for i in values if i ==‘0’])/len(values) #查看下载的百分比
print(baifen)
time.sleep(5)
###设置下载状态
r.set(‘status’,‘start’) #开始下载
r.set(‘status’,‘stop’) #停止下载
####################################从节点slaver(N个)
from redis import StrictRedis
import requests
import time
from lxml.etree import HTML
r=StrictRedis(host=‘localhost’,decode_responses=True,port=6379)#链接数据库
keys=r.hkeys(‘urls’)#从redis数据库中读取所有url
while True:
status =r.get(‘status’)
if status !=‘start’:
time.sleep(5)
print(‘停止中’)
continue
print(‘开始。。。。’)
for i in keys:
status = r.get(‘status’)
if status != ‘start’:
print(‘主机停止’)
break
#下载之前检查redis的状态
v=r.hget(‘urls’,i)
if v==‘1’ or v==‘3’:
try:
rst=requests.get(i,timeout=5)
rst.encoding=‘GB2312’
rst=rst.text
html=HTML(rst)
ls1=html.xpath(’/html/body/div[3]/div[2]/div[2]/div/div[1]/h1/@title’)#岗位
ls2=html.xpath(’/html/body/div[3]/div[2]/div[2]/div/div[1]/p[1]/a[1]/@title’)#公司
ls3=html.xpath(’/html/body/div[3]/div[2]/div[2]/div/div[1]/strong/text()’)#薪资
ls4=html.xpath(’/html/body/div[3]/div[2]/div[2]/div/div[1]/p[2]/@title’)#详情
r.hset('前程无忧',i[i.rindex('/')+1:i.rindex('?')],ls1[0]+'\t'+ls2[0]+'\t'+ls3[0]+'\t'+ls4[0])
**#网页保存到硬盘**
with open(i[i.rindex('/')+1:i.rindex('?')],'w',encoding='GB2312') as f:
f.write(rst)
#下载成功更改数据库状态 成功下载为0 失败为3
r.hset('urls',i,'0')
print('ok')
except Exception as err:
print('失败')
r.hset('urls',i,'3')