爬虫(六):案例:爬取扇贝英语单词+爬取网易云所有歌手+爬取酷狗音乐所有歌手

本文主要是介绍爬虫(六):案例:爬取扇贝英语单词+爬取网易云所有歌手+爬取酷狗音乐所有歌手,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 爬取网站的流程
    • 案例一:使用xpath爬取扇贝英语单词
    • 案例二:爬取网易云音乐的所有歌手名字
    • 案例三:爬取酷狗音乐的歌手和歌单

爬取网站的流程

  • 确定网站的哪个url是数据的来源
  • 简要分析一下网站结构,查看数据存放在哪里
  • 查看是否有分页,并解决分页的问题
  • 发送请求,查看response.text是否有我们所需要的数据
  • 筛选数据

案例一:使用xpath爬取扇贝英语单词

需求:爬取三页单词
在这里插入图片描述

import jsonimport requests
from lxml import etree
base_url = 'https://www.shanbay.com/wordlist/110521/232414/?page=%s'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
}def get_text(value):if value:return value[0]return ''word_list = []
for i in range(1, 4):# 发送请求response = requests.get(base_url % i, headers=headers)# print(response.text)html = etree.HTML(response.text)tr_list = html.xpath('//tbody/tr')# print(tr_list)for tr in tr_list:item = {}#构造单词列表en = get_text(tr.xpath('.//td[@class="span2"]/strong/text()'))tra = get_text(tr.xpath('.//td[@class="span10"]/text()'))print(en, tra)if en:item[en] = traword_list.append(item)

面向对象:

import requests
from lxml import etreeclass Shanbei(object):def __init__(self):self.base_url = 'https://www.shanbay.com/wordlist/110521/232414/?page=%s'self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'}self.word_list = []self.parse()def get_text(self, value):# 防止为空报错if value:return value[0]return ''def parse(self):for i in range(1, 4):# 发送请求response = requests.get(self.base_url % i, headers=self.headers)# print(response.text)html = etree.HTML(response.text)tr_list = html.xpath('//tbody/tr')# print(tr_list)for tr in tr_list:item = {}  # 构造单词列表en = self.get_text(tr.xpath('.//td[@class="span2"]/strong/text()'))tra = self.get_text(tr.xpath('.//td[@class="span10"]/text()'))print(en, tra)if en:item[en] = traself.word_list.append(item)shanbei = Shanbei()

案例二:爬取网易云音乐的所有歌手名字

在这里插入图片描述
在这里插入图片描述

import requests,json
from lxml import etreeurl = 'https://music.163.com/discover/artist'
singer_infos = []# ---------------通过url获取该页面的内容,返回xpath对象
def get_xpath(url):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'}response = requests.get(url, headers=headers)return etree.HTML(response.text)# --------------通过get_xpath爬取到页面后,我们获取华宇,华宇男等分类
def parse():html = get_xpath(url)fenlei_url_list = html.xpath('//ul[@class="nav f-cb"]/li/a/@href')  # 获取华宇等分类的url# print(fenlei_url_list)# --------将热门和推荐两栏去掉筛选new_list = [i for i in fenlei_url_list if 'id' in i]for i in new_list:fenlei_url = 'https://music.163.com' + iparse_fenlei(fenlei_url)# print(fenlei_url)# -------------通过传入的分类url,获取A,B,C页面内容
def parse_fenlei(url):html = get_xpath(url)# 获得字母排序,每个字母的链接zimu_url_list = html.xpath('//ul[@id="initial-selector"]/li[position()>1]/a/@href')for i in zimu_url_list:zimu_url = 'https://music.163.com' + iparse_singer(zimu_url)# ---------------------传入获得的字母链接,开始爬取歌手内容
def parse_singer(url):html = get_xpath(url)item = {}singer_names = html.xpath('//ul[@id="m-artist-box"]/li/p/a/text()')# --详情页看到页面结构会有两个a标签,所以取第一个singer_href = html.xpath('//ul[@id="m-artist-box"]/li/p/a[1]/@href')# print(singer_names,singer_href)for i, name in enumerate(singer_names):item['歌手名'] = nameitem['音乐链接'] = 'https://music.163.com' + singer_href[i].strip()# 获取歌手详情页的链接url = item['音乐链接'].replace(r'?id', '/desc?id')# print(url)parse_detail(url, item)print(item)# ---------获取详情页url和存着歌手名字和音乐列表的字典,在字典中添加详情页数据
def parse_detail(url, item):html = get_xpath(url)desc_list = html.xpath('//div[@class="n-artdesc"]/p/text()')item['歌手信息'] = desc_listsinger_infos.append(item)write_singer(item)# ----------------将数据字典写入歌手文件
def write_singer(item):with open('singer.json', 'a+', encoding='utf-8') as file:json.dump(item,file)if __name__ == '__main__':parse()

面向对象

import json, requests
from lxml import etreeclass Wangyiyun(object):def __init__(self):self.url = 'https://music.163.com/discover/artist'self.singer_infos = []self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'}self.parse()# ---------------通过url获取该页面的内容,返回xpath对象def get_xpath(self, url):response = requests.get(url, headers=self.headers)return etree.HTML(response.text)# --------------通过get_xpath爬取到页面后,我们获取华宇,华宇男等分类def parse(self):html = self.get_xpath(self.url)fenlei_url_list = html.xpath('//ul[@class="nav f-cb"]/li/a/@href')  # 获取华宇等分类的url# print(fenlei_url_list)# --------将热门和推荐两栏去掉筛选new_list = [i for i in fenlei_url_list if 'id' in i]for i in new_list:fenlei_url = 'https://music.163.com' + iself.parse_fenlei(fenlei_url)# print(fenlei_url)# -------------通过传入的分类url,获取A,B,C页面内容def parse_fenlei(self, url):html = self.get_xpath(url)# 获得字母排序,每个字母的链接zimu_url_list = html.xpath('//ul[@id="initial-selector"]/li[position()>1]/a/@href')for i in zimu_url_list:zimu_url = 'https://music.163.com' + iself.parse_singer(zimu_url)# ---------------------传入获得的字母链接,开始爬取歌手内容def parse_singer(self, url):html = self.get_xpath(url)item = {}singer_names = html.xpath('//ul[@id="m-artist-box"]/li/p/a/text()')# --详情页看到页面结构会有两个a标签,所以取第一个singer_href = html.xpath('//ul[@id="m-artist-box"]/li/p/a[1]/@href')# print(singer_names,singer_href)for i, name in enumerate(singer_names):item['歌手名'] = nameitem['音乐链接'] = 'https://music.163.com' + singer_href[i].strip()# 获取歌手详情页的链接url = item['音乐链接'].replace(r'?id', '/desc?id')# print(url)self.parse_detail(url, item)print(item)# ---------获取详情页url和存着歌手名字和音乐列表的字典,在字典中添加详情页数据def parse_detail(self, url, item):html = self.get_xpath(url)desc_list = html.xpath('//div[@class="n-artdesc"]/p/text()')[0]item['歌手信息'] = desc_listself.singer_infos.append(item)self.write_singer(item)# ----------------将数据字典写入歌手文件def write_singer(self, item):with open('sing.json', 'a+', encoding='utf-8') as file:json.dump(item, file)music = Wangyiyun()

案例三:爬取酷狗音乐的歌手和歌单

需求:爬取酷狗音乐的歌手和歌单和歌手简介
在这里插入图片描述

import json, requests
from lxml import etreebase_url = 'https://www.kugou.com/yy/singer/index/%s-%s-1.html'
# ---------------通过url获取该页面的内容,返回xpath对象
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
}# ---------------通过url获取该页面的内容,返回xpath对象
def get_xpath(url, headers):try:response = requests.get(url, headers=headers)return etree.HTML(response.text)except Exception:print(url, '该页面没有相应!')return ''# --------------------通过歌手详情页获取歌手简介
def parse_info(url):html = get_xpath(url, headers)info = html.xpath('//div[@class="intro"]/p/text()')return info# --------------------------写入方法
def write_json(value):with open('kugou.json', 'a+', encoding='utf-8') as file:json.dump(value, file)# -----------------------------用ASCII码值来变换abcd...
for j in range(97, 124):# 小写字母为97-122,当等于123的时候我们按歌手名单的其他算,路由为nullif j < 123:p = chr(j)else:p = "null"for i in range(1, 6):response = requests.get(base_url % (i, p), headers=headers)# print(response.text)html = etree.HTML(response.text)# 由于数据分两个url,所以需要加起来数据列表name_list1 = html.xpath('//ul[@id="list_head"]/li/strong/a/text()')sing_list1 = html.xpath('//ul[@id="list_head"]/li/strong/a/@href')name_list2 = html.xpath('//div[@id="list1"]/ul/li/a/text()')sing_list2 = html.xpath('//div[@id="list1"]/ul/li/a/@href')singer_name_list = name_list1 + name_list2singer_sing_list = sing_list1 + sing_list2# print(singer_name_list,singer_sing_list)for i, name in enumerate(singer_name_list):item = {}item['名字'] = nameitem['歌单'] = singer_sing_list[i]# item['歌手信息']=parse_info(singer_sing_list[i])#被封了write_json(item)

面向对象:

import json, requests
from lxml import etreeclass KuDog(object):def __init__(self):self.base_url = 'https://www.kugou.com/yy/singer/index/%s-%s-1.html'self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'}self.parse()# ---------------通过url获取该页面的内容,返回xpath对象def get_xpath(self, url, headers):try:response = requests.get(url, headers=headers)return etree.HTML(response.text)except Exception:print(url, '该页面没有相应!')return ''# --------------------通过歌手详情页获取歌手简介def parse_info(self, url):html = self.get_xpath(url, self.headers)info = html.xpath('//div[@class="intro"]/p/text()')return info[0]# --------------------------写入方法def write_json(self, value):with open('kugou.json', 'a+', encoding='utf-8') as file:json.dump(value, file)# -----------------------------用ASCII码值来变换abcd...def parse(self):for j in range(97, 124):# 小写字母为97-122,当等于123的时候我们按歌手名单的其他算,路由为nullif j < 123:p = chr(j)else:p = "null"for i in range(1, 6):response = requests.get(self.base_url % (i, p), headers=self.headers)# print(response.text)html = etree.HTML(response.text)# 由于数据分两个url,所以需要加起来数据列表name_list1 = html.xpath('//ul[@id="list_head"]/li/strong/a/text()')sing_list1 = html.xpath('//ul[@id="list_head"]/li/strong/a/@href')name_list2 = html.xpath('//div[@id="list1"]/ul/li/a/text()')sing_list2 = html.xpath('//div[@id="list1"]/ul/li/a/@href')singer_name_list = name_list1 + name_list2singer_sing_list = sing_list1 + sing_list2# print(singer_name_list,singer_sing_list)for i, name in enumerate(singer_name_list):item = {}item['名字'] = nameitem['歌单'] = singer_sing_list[i]# item['歌手信息']=parse_info(singer_sing_list[i])#被封了print(item)self.write_json(item)music = KuDog()

在这里插入图片描述

这篇关于爬虫(六):案例:爬取扇贝英语单词+爬取网易云所有歌手+爬取酷狗音乐所有歌手的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/836900

相关文章

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

MyBatis分页查询实战案例完整流程

《MyBatis分页查询实战案例完整流程》MyBatis是一个强大的Java持久层框架,支持自定义SQL和高级映射,本案例以员工工资信息管理为例,详细讲解如何在IDEA中使用MyBatis结合Page... 目录1. MyBATis框架简介2. 分页查询原理与应用场景2.1 分页查询的基本原理2.1.1 分

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

Java 正则表达式的使用实战案例

《Java正则表达式的使用实战案例》本文详细介绍了Java正则表达式的使用方法,涵盖语法细节、核心类方法、高级特性及实战案例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录一、正则表达式语法详解1. 基础字符匹配2. 字符类([]定义)3. 量词(控制匹配次数)4. 边

Python Counter 函数使用案例

《PythonCounter函数使用案例》Counter是collections模块中的一个类,专门用于对可迭代对象中的元素进行计数,接下来通过本文给大家介绍PythonCounter函数使用案例... 目录一、Counter函数概述二、基本使用案例(一)列表元素计数(二)字符串字符计数(三)元组计数三、C

Spring Boot 整合 SSE(Server-Sent Events)实战案例(全网最全)

《SpringBoot整合SSE(Server-SentEvents)实战案例(全网最全)》本文通过实战案例讲解SpringBoot整合SSE技术,涵盖实现原理、代码配置、异常处理及前端交互,... 目录Spring Boot 整合 SSE(Server-Sent Events)1、简述SSE与其他技术的对

MySQL 临时表与复制表操作全流程案例

《MySQL临时表与复制表操作全流程案例》本文介绍MySQL临时表与复制表的区别与使用,涵盖生命周期、存储机制、操作限制、创建方法及常见问题,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随小... 目录一、mysql 临时表(一)核心特性拓展(二)操作全流程案例1. 复杂查询中的临时表应用2. 临时

MySQL 数据库表与查询操作实战案例

《MySQL数据库表与查询操作实战案例》本文将通过实际案例,详细介绍MySQL中数据库表的设计、数据插入以及常用的查询操作,帮助初学者快速上手,感兴趣的朋友跟随小编一起看看吧... 目录mysql 数据库表操作与查询实战案例项目一:产品相关数据库设计与创建一、数据库及表结构设计二、数据库与表的创建项目二:员

C#中的Drawing 类案例详解

《C#中的Drawing类案例详解》文章解析WPF与WinForms的Drawing类差异,涵盖命名空间、继承链、常用类及应用场景,通过案例展示如何创建带阴影圆角矩形按钮,强调WPF的轻量、可动画特... 目录一、Drawing 是什么?二、典型用法三、案例:画一个“带阴影的圆角矩形按钮”四、WinForm

setsid 命令工作原理和使用案例介绍

《setsid命令工作原理和使用案例介绍》setsid命令在Linux中创建独立会话,使进程脱离终端运行,适用于守护进程和后台任务,通过重定向输出和确保权限,可有效管理长时间运行的进程,本文给大家介... 目录setsid 命令介绍和使用案例基本介绍基本语法主要特点命令参数使用案例1. 在后台运行命令2.