当前位置: 首页 > 图灵资讯 > 行业资讯> 爬取动漫图片:以后就有好看的桌面背景啦

爬取动漫图片:以后就有好看的桌面背景啦

来源:图灵python
时间: 2025-02-27 18:40:03

正文

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

importrequestsasr
importre
importos
importtime
file_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."}

resp=r.get(url,headers=headers)
html=resp.text

images=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).content
try:
withopen(file_name+'/'+name+'.jpg','wb')asf:
f.write(i)
exceptFileNotFoundError:
continue

先导入要使用的库

importrequestsasr
importre
importos
importtime

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

下图显示了网站的内容:01.jpg

好了 url已经确定了

下面去寻找headerss02.jpg

以下是代码显示

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."
}

然后检索要爬的图片内容

03.jpg

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

然后用正则表达式re进行检索

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

最后,把它保存起来

i=r.get(image,headers=headers).content
withopen(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)

有关python的更多文章,请关注python自学网。