小爬虫程序协程版

import gevent
from gevent import monkey
import requests,time,re,os
"""

协程爬虫的意义在于解决堵塞的耗时操作,epoll机制
不过用gevent好像不错,先来看下gevent的概念
其原理是当一个greenlet遇到IO(指的是input output 输入输出,比如网络、文件操作等)操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。
协程的意义就是跳过一些耗时操作,提升整体效率把,好像还挺有用的。
但是这个执行会容易引起访问间隔时间过短,而造成访问量大被封ip
"""

package_list = []
package_list2 = []
# 1.每页的url从1-531,使用for循环 拼接url
# 2.打开url之后,使用正则findall抓取该页的具体包链接 ,存入package_list


def get_pic_url(page,list):
try:
os.mkdir(str(page))
except Exception as e:
pass
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36'}
url = 'http://www.doutula.com/article/list/?page={}'.format(page)
res = requests.get(url,headers = head)
tmp = re.findall(r'<a href="([^#].*?)" class=".*?">', res.text)
print(tmp)
list.extend(tmp)
# 3.使用for循环遍历package_list 作为picture_url
# 4.打开改url ,然后抓取url中的表情jpg,存入本地文件夹或者数据库
for pic_url in list:
if len(pic_url) != len('http://www.doutula.com/article/detail/1070805'):
break
else:
res_pic = requests.get(pic_url,headers = head)
reg = r'''<img src="(.*?)" alt="(.*?)" .*?>'''
reg = re.compile(reg,re.S)
tmp = re.findall(reg,res_pic.text)

print(tmp)

for i in tmp:
num = tmp.index(i)
picture_res = requests.get(i[0],headers = head)
string = ''
if picture_res:
tmp_str = i[1]
for each in tmp_str:
if each in ('\\','/','*','?','"','|','>','<'):
pass
else:
string = string + each
tmp_str = string
if tmp_str[-3:] == 'jpg':
with open(r'./{}/{}-{}{}.jpg'.format(page,list.index(pic_url),num,tmp_str),'wb') as f:
f.write(picture_res.content)
time.sleep(1)
else:
with open(r'./{}/{}-{}{}.gif'.format(page,list.index(pic_url),num,tmp_str),'wb') as f:
f.write(picture_res.content)
time.sleep(1)
else:
break
list.clear()


def fun1():
for page in range(1,265): # 一共532
get_pic_url(page,package_list)


def fun2():
for page in range(265,532): # 一共532
get_pic_url(page,package_list2)

monkey.patch_all() # 将程序中用到的耗时操作的代码,换为gevent中自己实现的模块

gevent.joinall([
gevent.spawn(fun1),
gevent.spawn(fun2)
])

猜你喜欢

转载自www.cnblogs.com/guducp/p/9061506.html
今日推荐