青春有你2里面有很多漂亮的小姐姐,视频看起来很养眼,但所谓外行看热闹,既然数据分析这么强,我们也来用python分析下,看看我们能得到什么意外惊喜。
既然要做数据分析,那首先就先要获取数据,这篇文章我们先来介绍如何获取数据?我们使用爬虫来爬取参赛选手的信息,储存到JSON文件里,为后面发数据分析做准备。
我们先来了解下爬虫的过程:
1. 发送请求(requests模块) 2. 获取响应数据(服务器返回) 3. 解析并提取数据(BeautifulSoup查找或者re正则) 4. 保存数据
我们使用到的模块:
request模块
1. requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/
2. requests.get(url)可以发送一个http get请求,返回服务器响应内容。
BeautifulSoup库
1. BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库,网址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
2. BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是lxml
3. BeautifulSoup(markup,"html.parser")或者BeautifulSoup(markup,"lxml"),推荐使用lxml作为解析器,因为效率更高
下面我们就来一步一步实现爬取数据。
1
爬取《青春有你2》参赛选手信息,返回html
我们在浏览器打开网址https://baike.baidu.com/item/青春有你第二季,然后按F12打开调试工具,找到参赛学员表格,发现如下图table里面就是参赛学员信息,但是我们没法用class为 table-view log-set-param去直接提取到这张表格,因为通过这个class会有提取到7张表格,因为每张表格的名字不一样,所以我们通过这个class找出所有的表格后,进一步去判断表格的名字来得到参赛选手表格。
爬取参赛选手信息代码:
import json
import requestsimport datetimefrom bs4
import BeautifulSoup
import os
def crawl_player_data():
"""
爬取百度百科中《青春有你2》中参赛选手信息,返回html
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'
}
url = 'https://baike.baidu.com/item/青春有你第二季'
try:
response = requests.get(url, headers=headers)
# print(response.status_code)
# 将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串, 这里我们使用lxml解析器,效率比较高
soup = BeautifulSoup(response.text, 'lxml')
# 返回的是class为table-view log-set-param的所有<table>标签
tables = soup.find_all('table', {'class': 'table-view log-set-param'})
crawl_table_title = "参赛学员"
# 在找到的所有table里面去找table名字为"参赛学员"的table
for table in tables:
# 对当前table节点前面的标签和字符串进行查找,如果表名字是“参赛学员”,就返回这个table
table_titles = table.find_previous('div').find_all('h3')
for title in table_titles:
if crawl_table_title in title:
return table
except Exception as e:
print(e)
2
对爬取的页面进行解析,并保存为JSON文件
我们把上面爬取的table进行解析,保存为JSON文件,需要注意的一点是获取公司名时,方法会不一样,有的公司名字是有超链接的,会使用a标签, 没有超链接就没有a标签。
解析选手信息并存入JSON:
def parse_player_data(table_html):
"""
从百度百科返回的html中解析得到选手信息,以当前日期作为文件名,存JSON文件,保存到Day2data目录下
"""
bs = BeautifulSoup(str(table_html), 'lxml')
# 找到表格的所有行
all_trs = bs.find_all('tr')
# 用来处理字串里面的单引号和双引号
error_list = ['\'', '\"']
# 定义一个list,存放选手
stars = []
# 我们从第二行开始,第一行为表头,我们不需要
for tr in all_trs[1:]:
all_tds = tr.find_all('td')
# 定义一个字典,存放选手信息
star = dict()
# 姓名, 因为姓名里面有"\n"字串,所以需要处理掉
star["name"] = all_tds[0].text.replace("\n", "")
# 个人百度百科链接
star["link"] = 'https://baike.baidu.com' + all_tds[0].find('a').get('href')
# 籍贯
star["zone"] = all_tds[1].text
# 星座
star["constellation"] = all_tds[2].text
# 身高
star["height"] = all_tds[3].text
# 体重
star["weight"] = all_tds[4].text
# 花语,去除掉花语中的单引号或双引号
flower_word = all_tds[5].text
for c in flower_word:
if c in error_list:
flower_word = flower_word.replace(c, '')
star["flower_word"] = flower_word
# 公司, 公司的构成不一致,有超链接的会用到a标签,没有超链接的没有a标签,所以要做一下区分
if not all_tds[6].find('a') is None:
star["company"] = all_tds[6].find('a').text
else:
star["company"] = all_tds[6].text
# 把学员信息dict插入到学员列表中
stars.append(star)
# 保存数据到JSON文件
json_data = json.loads(str(stars).replace("\'", "\""))
with open('Day2Data/' + today + '.json', 'w', encoding='UTF-8') as f:
json.dump(json_data, f, ensure_ascii=False)
3
爬取每个选手的百度百科图片,并进行保存
我们保存了选手信息,根据选手信息里面的选手百度百科链接去爬取每位选手的图片并保存
def crawl_player_pics():
"""
爬取每个选手的百度百科图片,并保存
"""
with open('Day2Data/' + today + '.json', 'r', encoding='UTF-8') as fr:
json_array = json.loads(fr.read())
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'
}
for star in json_array:
name = star['name']
link = star['link']
print(link)
# 在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!
response = requests.get(link, headers=headers)
# print(response.text)
# 将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
soup = BeautifulSoup(response.text, 'lxml')
# 返回的是class为summary-pic的第一个<div>标签,这个里面有选手相册的地址
# 这里用find去找,而不是find_all,因为有个选手的页面没有任何信息,如果用find_all()[0]的话,会报错。
divs = soup.find('div', {'class': 'summary-pic'})
pic_urls = []
if divs:
# 对当前节点标签a进行查找
img_srcs = divs.find_all('a')[0]
# print(img_srcs)
# 这里我们找到相册的网址在去抓图片就可以抓到全部图片,如果我们只获取src的地址,就只能抓到一张照片
img_addr = img_srcs.get("href")
# print(img_addr)
response = requests.get('https://baike.baidu.com' + img_addr, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
# 返回的是class为pic-item的<a>所有标签,这个a标签里面就是所有照片的网址。
all_a = soup.find_all('a', {'class': 'pic-item'})
for a in all_a:
img_lists = a.find_all('img')
for img in img_lists:
img_addr = img.get("src")
# img_addr = img.get("data-sign")
# 这里我们把网址/resize后面的不要了,不然爬下来的是缩略图而不是大图。
img_addr = img_addr.split("/resize")[0]
# print(img_addr)
if img_addr:
pic_urls.append(img_addr)
# 根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!
down_pic(name, pic_urls)
def down_pic(name, pic_urls):
"""
根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
"""
path = 'Day2Data/' + 'pics/' + name + '/'
if not os.path.exists(path):
os.makedirs(path)
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(path + string, 'wb') as f:
f.write(pic.content)
print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
print(e)
continue
4
打印爬取的所有图片的路径
爬取了照片后,我们统计下爬取了多少张照片以及照片路径
def show_pic_path(path):
"""
遍历所爬取的每张图片,并打印所有图片的绝对路径
"""
pic_num = 0
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
pic_num += 1
print("第%d张照片:%s" % (pic_num, os.path.join(dirpath, filename)))
print("共爬取《青春有你2》选手的%d照片" % pic_num)
5
运行主函数
if __name__ == '__main__':
# 获取当天的日期,并进行格式化,用于后面文件命名,格式:20200420
today = datetime.date.today().strftime('%Y%m%d')
# print(today)
# 爬取百度百科中《青春有你2》中参赛选手信息,返回html
html = crawl_player_data()
# 解析html,得到选手信息,保存为json文件
parse_player_data(html)
# 从每个选手的百度百科页面上爬取图片,并保存
crawl_player_pics()
# 打印所爬取的选手图片路径
show_pic_path('Day2Data/pics/')
print("所有信息爬取完成!")
至此,我们得到了所有参赛选手的信息并保存了下来,下一篇我们将用这些信息去做一些分析,让这些数据可视化,看一下能挖掘到什么不一样的,然后更直接明白的显示给读者。