**
彼岸图网-图片爬取-仅供学习使用
**
彼岸图网
彼岸图网,这个是一个静态网站,就没什么好讲的,今天主要是教你怎么爬取图片。
- 找到图片的链接
- 请求这个图片的链接进行下载就好了
对,你没有看错,图片的爬取就是这么简单。
这里就是图片的链接和名称了,我们只要获取图片的名称和图片的链接,再去请求图片的链接就可以将图片爬取到我们的电脑上面了。
下面这部分代码就是对图片的名称和链接进行提取,需要注意的是,我们这里提取的图片链接和图片名称是一个列表:
url = 'http://pic.netbian.com/e/search/result/index.php?page=0&searchid=1224'
response = requests.get(url,headers=headers)
# print(response.text)
html = parsel.Selector(response.text)
img_urls = html.xpath("//div[@class='slist']/ul/li/a/img/@src").getall()#获取图片链接
names = html.xpath("//div[@class='slist']/ul/li/a/img/@alt").getall()#获取图片名字
对刚才提取到得到图片链接和图片名称进行处理,并请求图片链接,将图片爬取到本地。
for name,img_url in zip(names,img_urls):
name = re.findall('[\u4e00-\u9fa5]{1,10}', name)#提取中文:参数1:表示一组最少一个中文,参数10:表示一组最多10个中文
name = '-'.join(name)+'.png' #列表转成字符串
print(name)
# print(type(name))
img_url = "http://pic.netbian.com/" + img_url
print(img_url)
content = requests.get(img_url,headers=headers).content
with open(path+name,mode='wb') as fp:
fp.write(content)
这样,我们就轻松地对一页图片进行了爬取,下面我们要进行翻页操作,以爬取到更多的图片。这里利用for循环便可以轻松解决。
for i in range(0,564):
url = 'http://pic.netbian.com/e/search/result/index.php?page={}&searchid=1224'.format(i)
下面给出程序的完整代码:
#encoding: utf-8
#author : 渔戈
import re
import requests
import parsel
import os
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
'Referer':'http://pic.netbian.com/e/search/result/?searchid=1224'
}
# 定义保存路径
path = "F:\\Python爬虫\\爬虫实战\\图片爬取\\彼岸图网\\4k壁纸\\"#自定义位置
if not os.path.exists(path):
os.mkdir(path)
def spider():
for i in range(0,564):
url = 'http://pic.netbian.com/e/search/result/index.php?page={}&searchid=1224'.format(i)
response = requests.get(url,headers=headers)
# print(response.text)
html = parsel.Selector(response.text)
img_urls = html.xpath("//div[@class='slist']/ul/li/a/img/@src").getall()#获取图片链接
names = html.xpath("//div[@class='slist']/ul/li/a/img/@alt").getall()#获取图片名字
for name,img_url in zip(names,img_urls):
name = re.findall('[\u4e00-\u9fa5]{1,10}', name)
name = '-'.join(name)+'.png'
print(name)
# print(type(name))
img_url = "http://pic.netbian.com/" + img_url
print(img_url)
content = requests.get(img_url,headers=headers).content
with open(path+name,mode='wb') as fp:
fp.write(content)
if __name__ == '__main__':
spider()
运行我们的爬虫程序,我们可以看到,程序正在快速爬取图片:
好了,本次的图片爬虫小案例就到此结束了,谢谢观看,鞠躬.jpg。