2020-3-15 17:05发表于吾爱破解
废话不多说,直接上代码。最近还学了多线程同时爬的,但是没学透,晚点再发对比代码上来。
import requests,os,re
from bs4 import BeautifulSoup
a=requests.get('https://www.enterdesk.com/')
b=BeautifulSoup(a.text,'lxml')
d=b.find_all('div',class_='egene_pic_li')
for i in d:
e=i.find('a')['href'] #提取主页编辑推荐专栏所有链接
t=i.find('img')['alt'] #标题
num = re.sub(r'\W', "", t) #移除多余的标点符号,防止创建目录报错
#创建目录
path='C:/Users/Administrator/Desktop/图/'
es = os.path.exists(path+num)
if not es:
os.makedirs(path+num)
print('%s 下载中。。。'%num)
else:
print('已存在,跳过。。。')
pass
a1=requests.get(e)
b1=BeautifulSoup(a1.text,'lxml')
d1=b1.find_all('div',class_='swiper-slide')
for j in d1:
e1=j.find('a')['src'] #图片链接
a2=requests.get(e1).content #转成二进制
with open(path+num+'/'+e1[50:],'wb') as f: #随便取50个字符之后的字符作为名字
f.write(a2)
这是对比代码,速度确实快了很多,但是请慎用,毕竟这样大流量会拖垮别人服务器的
import gevent
from gevent import monkey
monkey.patch_all() #从gevent库里导入monkey模块
from gevent.queue import Queue
monkey.patch_all()
import requests,re,os,time
from bs4 import BeautifulSoup
q=time.time()
url_list=[]
work = Queue() #创建队列对象,并赋值给work
a=requests.get('https://www.enterdesk.com/')
b=BeautifulSoup(a.text,'lxml')
d=b.find_all('div',class_='egene_pic_li')
h=0
for i in d:
h+=1
e=i.find('a')['href'] #提取主页编辑推荐专栏所有链接
if 1<h<9:
t=i.find('img')['alt'] #标题
num = re.sub(r'\W', "", t) #移除多余的标点符号,防止创建目录报错
#创建目录
path='C:/Users/Administrator/Desktop/图/'
es = os.path.exists(path+num)
if not es:
os.makedirs(path+num)
print('%s 下载中。。。'%num)
else:
print('已存在,跳过。。。')
pass
a1=requests.get(e)
b1=BeautifulSoup(a1.text,'lxml')
d1=b1.find_all('div',class_='swiper-slide')
for j in d1:
e1=j.find('a')['src'] #图片链接
work.put_nowait(e1) # 用put_nowait()函数可以把网址都放进队列里
else:
pass
def a():
while not work.empty(): # 当队列不是空的时候,就执行下面的程序
e1 = work.get_nowait() # 用get_nowait()函数可以把队列里的网址都取出
a2 = requests.get(e1).content # 转成二进制
print(e1,work.qsize()) #打印网址、队列长度、抓取请求的状态码
#print(path + num)
with open(path + num + '/' + e1[50:], 'wb') as f: # 随便取50个字符之后的字符作为名字
f.write(a2)
tasks_list = [ ]
for x in range(5): #相当于创建了5个爬虫
task = gevent.spawn(a) #用gevent.spawn()函数创建执行crawler()函数的任务
tasks_list.append(task) #往任务列表添加任务。
gevent.joinall(tasks_list) #用gevent.joinall方法,执行任务列表里的所有任务,就是让爬虫开始爬取网站
q1=time.time()
print(q1-q)
:exclaim: