Day2-《青春有你2》选手信息爬取
作业:青春有你2》选手图片爬取,将爬取图片进行保存
作业代码如下:
ef crawl_pic_urls():
'''
爬取每个选手的百度百科图片,并保存
'''
with open('work/'+ today + '.json', 'r', encoding='UTF-8') as file:
json_array = json.loads(file.read())
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
for star in json_array:
name = star['name']
# link为每个参赛选手的个人链接
link = star['link']
#!!!请在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!!!
#使用request获取参赛选手个人链接响应结果
response = requests.get(link,headers=headers)
soup = BeautifulSoup(response.text,'lxml')
# 使用get_url 获取参赛选手图集链接
get_url = 'https://baike.baidu.com' +soup.find_all('div',{'class':'summary-pic'})[0].find('a').get('href')
# 使用request获取参赛选手图集链接响应结果
next_response = requests.get(get_url,headers=headers)
next_soup = BeautifulSoup(next_response.text,'lxml')
# 定义图片链接列表pic_urls
pic_urls = []
# 获取pic-list下的所有包含img元素的列表
get_img_list = next_soup.find_all('div',{'class':'pic-list'})[0].find_all('img')
for ele in get_img_list:
# 通过get('src')获取对应的图片链接
pic_url = ele.get('src')
pic_urls.append(pic_url)
#!!!根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!!!
down_pic(name,pic_urls)
代码详解
步骤一
link = star['link']
get_url = 'https://baike.baidu.com' +soup.find_all('div',{'class':'summary-pic'})[0].find('a').get('href')
link为每个参赛选手的个人网页链接,以刘亚楠为例:https://baike.baidu.com/item/刘亚楠/24271343
点击该链接,进入个人界面后,F12进入开发者模式
在这里插入图片描述
点击红框的箭头后,再次点击选手图册,就可以看到summary-pic这个标签和图集的网页链接。
需要注意href中拿到的网页链接没有’https://baike.baidu.com’,因此加上后才能成为图集的链接。
soup.find_all()的返回结果为列表,所以需要取其中的第一个元素即可。
find(‘a’).get(‘href’) 获取其中a标签下的href
步骤二
拿到图集链接后,使用以下代码获取跳转后页面的所有元素
next_response = requests.get(get_url,headers=headers)
next_soup = BeautifulSoup(next_response.text,'lxml')
如同上一步中的操作,获取图片的标签pic-list
find_all()获取的是一个列表,因为本页中只有一个pic-list元素,所以取列表的第一个元素即可。
再利用find_all(‘img’)获取所有包含img的列表。
最后遍历拿到的get_img_list列表,获取相应的图片链接即可。
get_img_list = next_soup.find_all('div',{'class':'pic-list'})[0].find_all('img')
for ele in get_img_list:
# 通过get('src')获取对应的图片链接
pic_url = ele.get('src')
pic_urls.append(pic_url)