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

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

文章目录

  • 爬取网站的流程
    • 案例一:使用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

相关文章

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

【区块链 + 人才服务】可信教育区块链治理系统 | FISCO BCOS应用案例

伴随着区块链技术的不断完善,其在教育信息化中的应用也在持续发展。利用区块链数据共识、不可篡改的特性, 将与教育相关的数据要素在区块链上进行存证确权,在确保数据可信的前提下,促进教育的公平、透明、开放,为教育教学质量提升赋能,实现教育数据的安全共享、高等教育体系的智慧治理。 可信教育区块链治理系统的顶层治理架构由教育部、高校、企业、学生等多方角色共同参与建设、维护,支撑教育资源共享、教学质量评估、

[英语单词] paste

这个单词的意思,有时候可能会被,被copy/paste误导了,会有一种假象,只有copy了才可以paste。 其实还可以将两个东西paste在一起。比如下面的: /kernel/include/linux/compiler_types.h /* Indirect macros required for expanded argument pasting, eg. __LINE__. */#d

客户案例:安全海外中继助力知名家电企业化解海外通邮困境

1、客户背景 广东格兰仕集团有限公司(以下简称“格兰仕”),成立于1978年,是中国家电行业的领军企业之一。作为全球最大的微波炉生产基地,格兰仕拥有多项国际领先的家电制造技术,连续多年位列中国家电出口前列。格兰仕不仅注重业务的全球拓展,更重视业务流程的高效与顺畅,以确保在国际舞台上的竞争力。 2、需求痛点 随着格兰仕全球化战略的深入实施,其海外业务快速增长,电子邮件成为了关键的沟通工具。

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

Python3 BeautifulSoup爬虫 POJ自动提交

POJ 提交代码采用Base64加密方式 import http.cookiejarimport loggingimport urllib.parseimport urllib.requestimport base64from bs4 import BeautifulSoupfrom submitcode import SubmitCodeclass SubmitPoj():de

STL经典案例(四)——实验室预约综合管理系统(项目涉及知识点很全面,内容有点多,耐心看完会有收获的!)

项目干货满满,内容有点过多,看起来可能会有点卡。系统提示读完超过俩小时,建议分多篇发布,我觉得分篇就不完整了,失去了这个项目的灵魂 一、需求分析 高校实验室预约管理系统包括三种不同身份:管理员、实验室教师、学生 管理员:给学生和实验室教师创建账号并分发 实验室教师:审核学生的预约申请 学生:申请使用实验室 高校实验室包括:超景深实验室(可容纳10人)、大数据实验室(可容纳20人)、物联网实验

Python:豆瓣电影商业数据分析-爬取全数据【附带爬虫豆瓣,数据处理过程,数据分析,可视化,以及完整PPT报告】

**爬取豆瓣电影信息,分析近年电影行业的发展情况** 本文是完整的数据分析展现,代码有完整版,包含豆瓣电影爬取的具体方式【附带爬虫豆瓣,数据处理过程,数据分析,可视化,以及完整PPT报告】   最近MBA在学习《商业数据分析》,大实训作业给了数据要进行数据分析,所以先拿豆瓣电影练练手,网络上爬取豆瓣电影TOP250较多,但对于豆瓣电影全数据的爬取教程很少,所以我自己做一版。 目