小爬虫程序进程版
Posted guducp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小爬虫程序进程版相关的知识,希望对你有一定的参考价值。
import multiprocessing,requests,time,re,os
"""
其实在我的项目内和多线程差不多,多进程多个进程之间不共享全局变量
所以意思是我只需要一个全局变量就可以
"""
package_list = []
# 1.每页的url从1-531,使用for循环 拼接url
# 2.打开url之后,使用正则findall抓取该页的具体包链接 ,存入package_list
def get_pic_url(page):
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)
package_list.extend(tmp)
# 3.使用for循环遍历package_list 作为picture_url
# 4.打开改url ,然后抓取url中的表情jpg,存入本地文件夹或者数据库
for pic_url in package_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,package_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,package_list.index(pic_url),num,tmp_str),‘wb‘) as f:
f.write(picture_res.content)
time.sleep(1)
else:
break
package_list.clear()
def fun1():
for page in range(1,265):
get_pic_url(page)
def fun2():
for page in range(265,532): # 一共532
get_pic_url(page)
if __name__ == "__main__":
t1 = multiprocessing.Process(target=fun1)
t2 = multiprocessing.Process(target=fun2)
t1.start()
t2.start()
# 成功完成
以上是关于小爬虫程序进程版的主要内容,如果未能解决你的问题,请参考以下文章