这篇博客是来自木林森的雪作者《简单的小爬虫-漫画爬取》
https://blog.csdn.net/qq_21049875/article/details/80526251#commentsedit
如果喜欢看漫画的程序员,可以分享学习一下,本次爬虫主要爬取了风之动漫的漫画资源,本文将在个人使用木林森的雪作者的代码中出现的一些问题进行分析并记录
import requests
import re
import os
import threading
import time
class fzdm:
addr="https://manhua.fzdm.com/"
def __init__(self,mhtype):
if isinstance(mhtype,str):
pass
else:
mhtype=str(mhtype)
self.m_thread=[]
self.type=mhtype
self.mhaddr=self.addr+mhtype
self.startpart="001"
r=requests.get(self.mhaddr)
pattern='href="(\d+)/"'
result=re.search(pattern,r.content.decode('utf-8'))
if result:
self.endpart=result.group(1)
def downloadPart(self,index):
if isinstance(index,str):
pass
else:
index=str(index)
start=0
url=self.mhaddr+"/"+index+"/"+"index_"+str(start)+".html"
while self.downloadImage(url) == False:
start+=1
url=self.mhaddr+"/"+index+"/"+"index_"+str(start)+".html"
def downloadPart_s_e(self,s="001",e=0):
if e == 0:
e=self.endpart
if isinstance(s,str) == False:
s=str(s)
if isinstance(e,str) == False:
e=str(e)
index=[]
while int(s)<=int(e):
tmp_thread=threading.Thread(target=fzdm.downloadPart,args=(self,s,))
#self.downloadPart(s)
tmp_thread.start()
self.m_thread.append(tmp_thread)
s=str(int(s)+1)
for i in self.m_thread:
i.join()
def downloadImage(self,url):
r=requests.get(url)
isendpattern='最后一页了'
result_isend=re.search(isendpattern,r.content.decode('utf-8'))
imgpattern='var mhurl="(\d+/\d+/\d+\.jpg)";'
result_img=re.search(imgpattern,r.content.decode('utf-8'))
indexpattern='(七原罪\d+话)'
result_mh=re.search(indexpattern,r.content.decode('utf-8'))
time.sleep(5)
if result_img:
mhname=result_mh.group(1)
img=result_img.group(1)
imgurl="http://p1.xiaoshidi.net/"+img
r=requests.get(imgurl)
time.sleep(5)
if os.path.exists("download/"+mhname):
pass
else:
os.mkdir("download/"+mhname)
filename=img.replace('/','.')
f=open("download/"+mhname+"/"+filename,"wb")
f.write(r.content)
f.close()
print('下载图片完成~')
if result_isend:
return True
else:
return False
a=fzdm("56")
a.downloadPart_s_e(277,278)
---------------------
本文来自 木林森的雪 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_21049875/article/details/80526251?utm_source=copy
代码中我们需要注意的就是URL地址的参数形式,对于爬取100话以后的内容时,代码没有任何问题,只需要更改对应的漫画对应的数字即可以及漫画名字,对于爬取1-99话时,URL地址的参数形式需要url=self.mhaddr+"/"+index+"/"+“index_”+str(start)+".html" 加上0或00,即
url=self.mhaddr+“00/”+index+"/"+“index_”+str(start)+".html"
如果没有加的话,因为没有正则表达式没有匹配到相应的URL地址对应的HTML,会出现以下错误,即
UnboundLocalError: local variable ‘mhname’ referenced before assignment ,除此之外,该代码可以爬取风之动漫上到任意资源,对于喜爱动漫的程序员可以学习一波哦。