记一次简单的爬虫学习

批量爬取 pixabay 图片

pixabay图片查找地址

pixabay网站提供的API


1. pixabay 是一个做的很好的免费图片获取网站,里边有很多高质量免费的图片,有一天我想能不能写一个批量获取图片的爬虫,用于收集那些漂亮图片

2. 说做就做,我先对网站进行最简单的分析(急性子,甚至源码都没细看),然后就开始急急切切的开始了爬取
1
2
3
4
5
6
7
8
9
import requests
from bs4 import BeautifulSoup

link = 'https://pixabay.com/zh/images/search/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/78.0.3904.97 Safari/537.36'}
response = requests.get(link, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
print(soup)
结果当然是失败了,并且基本上没有获得什么有用的信息

3. 然后再对网页源码报头进行仔细查看后仍然一头雾水的我,想到了可能会提供的有 API 接口,然后通过 CTRL + F在源码中搜索,找到了官方提供的 API 结构(赞美官方)

pixabay网站提供的API

通过阅读官方文档就能发现只需要注册官方就可以提供一个 API key,每小时下载量也够我这个个人用户使用

官方提供了非常详细的 网址的各种参量拼接方式,以及爬出样本以供分析(出乎意料的是还有影片的接口及查询方式)
对链接构成简单分析后,我发现对于自己需要提供的仅仅是KEY, 图片类型(image_type)搜索条件(q)爬取页数(page)每页爬取数(per_page)




于是一段简单的拼接 URL 构成了,也考虑到了翻页的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def get_json(page, condition, image_type):
page += 1
key = ''
url = 'https://pixabay.com/api/'

pa = {
'key': key,
'q': condition,
'image_type': image_type,
'lang': 'zh',
'page': page,
'per_page': 200,
}
r = requests.get(url, params=pa, headers=headers)
decode_json = json.loads(r.text)
return decode_json
4. 根据官方提供的例子进行分析,挑出自己需要的部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"type": "photo",
"tags": "blossom, bloom, flower",
"previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg",
"previewWidth": 150,
"previewHeight": 84,
"webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
"webformatWidth": 640,
"webformatHeight": 360,
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
"imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
"imageWidth": 4000,
"imageHeight": 2250,
"imageSize": 4731420,
"views": 7671,
"downloads": 6439,
"favorites": 1,
"likes": 5,
"comments": 2,
"user_id": 48777,
"user": "Josch13",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg"
},
{
"id": 73424
}
]
}
在这些里面我们需要的是 图片的类型、图片的标签、图片的大图链接 ,由于最近在学习数据分析,于是我也爬取了图片的下载量、收藏量以及被标记为爱好的量
1
2
3
4
5
6
7
data = {'type': picture['type'],
'tags': picture['tags'],
'largeImageURL': picture['largeImageURL'],
'downloads': picture['downloads'], # 下载总数
'favorites': picture['favorites'], # 收藏夹总数
'like': picture['likes'], # 点赞总数
}
然后就是对大体框架的编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import requests
import json
from pymongo import MongoClient
import time
import csv
import pymysql


def get_json(page, condition, image_type):
page += 1
key = ''
url = 'https://pixabay.com/api/'

pa = {
'key': key,
'q': condition,
'image_type': image_type,
'lang': 'zh',
'page': page,
'per_page': 200,
}
r = requests.get(url, params=pa, headers=headers)
decode_json = json.loads(r.text)
return decode_json


page = 0
id = 0
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/78.0.3904.97 Safari/537.36'}
condition = input("请输入你的搜索条件(多个条件以+连接): ")
image_type = input("请输入搜索图片类型( 'all, photo, illustration插图, vector矢量'): ")
number = input('请输入想要查询的图片页数num (num*200每页200条数据): ')

# 存入 Nosql 数据库
client = MongoClient('localhost', 27017)
db = client.pixabay_database
collection = db.pixabay
for _ in range(1, int(number)):
decode_json = get_json(page, condition, image_type)
for picture in decode_json['hits']:
id += 1
data = {'id': id,
'type': picture['type'],
'tags': picture['tags'],
'largeImageURL': picture['largeImageURL'],
'downloads': picture['downloads'], # 下载总数
'favorites': picture['favorites'], # 收藏夹总数
'like': picture['likes'], # 点赞总数
}
print('开始存入数据库')
collection.insert_one(data)
# 存入Mysql数据库
'''db = pymysql.connect(host='localhost',
user="root",
passwd="root",
port=3306,
db='pixabay',
charset='utf8')
cursor = db.cursor()
for _ in range(1, int(number)):
decode_json = get_json(page, condition, image_type)
for picture in decode_json['hits']:
id += 1
data = {'id': id,
'type': picture['type'],
'tags': picture['tags'],
'largeImageURL': picture['largeImageURL'],
'downloads': picture['downloads'], # 下载总数
'favorites': picture['favorites'], # 收藏夹总数
'like': picture['likes'], # 点赞总数
}
print('开始存入数据库')
sql = """INSERT INTO pixabay
(type, tags, largeImageURL, downloads, favorites, likes)
VALUES
(%s, %s, %s, %s, %s, %s)
"""
cursor.execute(sql, (
picture['type'], picture['tags'], picture['largeImageURL'], picture['downloads'], picture['favorites'],
picture['likes']))
db.commit()
# print(data)
cursor.close()
db.close()'''
# 存为 CSV 格式
'''with open('/helper_hu/analysis_pixabay/analysis_pixabay.csv', 'a+', encoding='UTF-8', newline='') as csvfile:
head = ['id', 'type', 'tags', 'largeImageURL', 'downloads', 'favorites', 'like']
writer = csv.writer(csvfile)
writer.writerow(head)
for _ in range(1, int(number)):
decode_json = get_json(page, condition, image_type)
for picture in decode_json['hits']:
id += 1
data = {'id': id,
'type': picture['type'],
'tags': picture['tags'],
'largeImageURL': picture['largeImageURL'],
'downloads': picture['downloads'], # 下载总数
'favorites': picture['favorites'], # 收藏夹总数
'like': picture['likes'], # 点赞总数
}
# head = list(data.keys())
rows = list(data.values())
writer.writerow(rows)
print('写入数据id={}'.format(id))
time.sleep(1.0)
'''



小结:分别写了3种存储方式 MySQL、MangoDB以及CSV,之后我用读取CSV 数据的方法简单分析了一类图片下用户最喜欢的图片以及下载量最多的。