爬虫实战1:爬取哔哩哔哩主播的头像以昵称命名保存到本地文件 您所在的位置:网站首页 PythonAPI输出头像怎么下载到文件夹 爬虫实战1:爬取哔哩哔哩主播的头像以昵称命名保存到本地文件

爬虫实战1:爬取哔哩哔哩主播的头像以昵称命名保存到本地文件

2023-08-08 08:21| 来源: 网络整理| 查看: 265

申明:资料来源于网络及书本,通过理解、实践、整理成学习笔记。

Pythion的Selenium自动化测试之获取哔哩哔哩主播的头像以昵称命名保存到本地文件

效果图

在这里插入图片描述

方法1

通过接口获取 首先使用pip下载requests包

pip install requests

在这里插入图片描述

import requests # 通过接口获取请求的接口:想要获取网页的url url = 'https://api.live.bilibili.com/xlive/web-interface/v1/second/getList?platform=web&parent_area_id=1&area_id=0&sort_type=sort_type_152&page=1' # 发送get请求,获取返回数据 request = requests.get(url) # 保存图片的路径 dir = '../requests/bilibili/' # 将获取的数据转化为json文件并获取到图片的链接 info = request.json()['data']['list'] for i in info: # 将图片以主播的昵称命名 file = open(dir + '{}.png'.format(i['uname']), 'wb') # 将图片保存到之前的路径 file.write(requests.get(i['face']).content) # 关闭文件流 file.close() 方法2

通过html定位获取 首先使用pip下载requests和selenium包

pip install requests pip install selenium

在这里插入图片描述

import requests from selenium import webdriver # 使用谷歌驱动打开谷歌浏览器 driver = webdriver.Chrome() # 访问哔哩哔哩直播页面 driver.get('https://live.bilibili.com/p/eden/area-tags?visit_id=2mwktlg4e2q0&areaId=0&parentAreaId=1') # 循环30次一次保存的头像图片 for i in range(1, 31): # xpth定位头像的位置 image_xpath = '/html/body/div[1]/div[3]/div/ul/li[{}]/a/div[1]/div/div'.format(i) # 获取位置的style属性值 image_style_value = driver.find_element_by_xpath(image_xpath).get_attribute('style') # 从style属性值中切片出图片的链接 image_url = image_style_value[image_style_value.find('h'):image_style_value.find('@'):1] # xpath定位昵称的位置 title_xpath = '/html/body/div[1]/div[3]/div/ul/li[{}]/a/div[2]/div[2]/div/span'.format(i) # 获取位置的title值 name_title_value = driver.find_element_by_xpath(title_xpath).get_attribute('title') print(image_url) # 发送get请求,获取返回数据 request = requests.get(image_url) # 保存图片的路径 file = open('D:Python Projects/requests/bilibili/{}.jpg'.format(name_title_value), 'wb') # 将图片保存到路径 file.write(request.content) # 关闭文件流 file.close()

Python爬虫实战专栏:

爬虫实战1:爬取哔哩哔哩主播的头像以昵称命名保存到本地文件

爬虫实战2:爬取CSDN作者总榜排名Top100保存到excel表

爬虫实战3:爬取天天基金的7663个基金排名保存到excel表

一个坚持学习,坚持成长,坚持分享的人,即使再不聪明,也一定会成为优秀的人!

如果看完觉得有所收获的话,记得一键三连哦,谢谢大家!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有