小编给大家分享一下如何爬取动漫图片,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨方法吧!

正文

话不多说,直接上完整代码

importrequestsasrimportreimportosimporttimefile_name="动漫截图"ifnotos.path.exists(file_name):os.mkdir(file_name)forpinrange(1,34):print("--------------------正在爬取第{}页内容------------------".format(p))url='https://www.acgimage.com/shot/recommend?page={}'.format(p)headers={"user-agent":"Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/80.0.3987.162Safari/537.36"}resp=r.get(url,headers=headers)html=resp.textimages=re.findall('data-original="(.*?)"',html)names=re.findall('title="(.*?)"',html)#print(images)#print(names)dic=dict(zip(images,names))forimageinimages:time.sleep(1)print(image,dic[image])name=dic[image]#name=image.split('/')[-1]i=r.get(image,headers=headers).contenttry:withopen(file_name+'/'+name+'.jpg','wb')asf:f.write(i)exceptFileNotFoundError:continue

先导入要使用的库

importrequestsasrimportreimportosimporttime

然后去分析要去爬的网址: 动漫截图网

下图是网址的内容:

好了 url已经确定

下面去寻找headers

找到下面是代码展示

url='https://www.acgimage.com/shot/recommend?page={}'.format(p)headers={"user-agent":"Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/80.0.3987.162Safari/537.36"}

然后检索要爬的图片内容

从上图就可以找到图片的位置:data-origina=后面的内容
以及图片的名字:title=后面的内容

然后用正则表达式re来检索就行了

images=re.findall('data-original="(.*?)"',html)names=re.findall('title="(.*?)"',html)

最后将其保存就好了

i=r.get(image,headers=headers).contentwithopen(file_name+'/'+name+'.jpg','wb')asf:f.write(i)

然后将page后面的数字改动就可以跳到相应的页面
换页的问题也就解决了

orpinrange(1,34):url='https://www.acgimage.com/shot/recommend?page={}'.format(p)

以及将爬到的图片放到自己建立的文件zh
使用了os库

file_name="动漫截图"ifnotos.path.exists(file_name):os.mkdir(file_name)



看完了这篇文章,相信你对如何爬取动漫图片有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!