爬取豆瓣音乐TOP250的数据
参考网址:https://music.douban.com/top250
因为详细页的信息更丰富,本次爬虫在详细页中进行,因此先爬取进入详细页的网址链接,进而爬取数据。
需要爬取的信息有:歌曲名、表演者、流派、发行时间、出版者和评分等。
将数据分别使用TXT、JSON、CSV存储。
import re
import csv
import time
import json
import requests
from bs4 import BeautifulSoup
from requests import RequestException def get_one_page(url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36'
+ '(KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
response = requests.get(url, headers=headers)
#response.encoding = response.apparent_encoding
if response.status_code == 200:
return response.text
return None
except RequestException:
return None def get_detailurl(text):
detailurl = []
soup = BeautifulSoup(text, 'lxml')
nbg = soup.find_all(name='a', class_='nbg')
for i in nbg:
detailurl.append(i['href'])
return detailurl def parse_one_page(text):
soup = BeautifulSoup(text, 'lxml') #使用lxml XML 解析库
performer = soup.select('#info > span > span > a')
#有标签没有属性的情况下用select, 否则用find_all
song = soup.select('#wrapper > h1 > span') style = re.findall('流派:</span> (.*?)<br', text, re.S) #.*?非贪婪匹配
#re.S使.匹配包括换行在内的所有字符
if len(style) == 0: #有的页面没有流派,用NULL填充
style.append('NULL')
publisher = re.findall('出版者:</span> (.*?)?<br', text, re.S)
if len(publisher) == 0: #有的页面没有出版者,用NULL填充
publisher.append('NULL')
pattern = re.compile('发行时间:</span> (.*?)?<br', re.S)
#compile()将正则字符串编译成正则对象,方便之后复用
time = re.findall(pattern, text) score = soup.find_all(name='strong', class_="ll rating_num")
#有标签有属性的情况下用find_all
yield {
'performer': performer[0].string,
'song': song[0].string,
'style': style[0].strip(),
'time': time[0].strip(),
'publisher': publisher[0].strip(),
'score': score[0].string,
} def write_to_file(content):
with open('doubanMusicTop250.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False)+'\n')
#dumps将json对象转化为字符串 def write_to_json(content):
with open('doubanMusicTop250.json', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False)+'\n') def write_to_csv(content):
with open('doubanMusicTop250.csv', 'a', encoding='utf-8') as f:
fieldnames = ['publisher', 'style', 'song', 'score', 'performer', 'time']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(content) if __name__ == '__main__':
url = 'https://music.douban.com/top250?start={}'
urls = [url.format(page) for page in range(0,256,25)]
content = []
for url in urls:
text1 = get_one_page(url)
detailurl = get_detailurl(text1)
for i in detailurl:
text2 = get_one_page(i)
for item in parse_one_page(text2):
print(item)
write_to_file(item)
content.append(item)
time.sleep(1)
write_to_csv(content)
write_to_json(content)
爬取豆瓣音乐TOP250的数据的更多相关文章
- Python爬虫小白入门(七)爬取豆瓣音乐top250
抓取目标: 豆瓣音乐top250的歌名.作者(专辑).评分和歌曲链接 使用工具: requests + lxml + xpath. 我认为这种工具组合是最适合初学者的,requests比pytho ...
- 实例学习——爬取豆瓣音乐TOP250数据
开发环境:(Windows)eclipse+pydev+MongoDB 豆瓣TOP网址:传送门 一.连接数据库 打开MongoDBx下载路径,新建名为data的文件夹,在此新建名为db的文件夹,d ...
- 一起学爬虫——通过爬取豆瓣电影top250学习requests库的使用
学习一门技术最快的方式是做项目,在做项目的过程中对相关的技术查漏补缺. 本文通过爬取豆瓣top250电影学习python requests的使用. 1.准备工作 在pycharm中安装request库 ...
- Python爬虫:现学现用xpath爬取豆瓣音乐
爬虫的抓取方式有好几种,正则表达式,Lxml(xpath)与BeautifulSoup,我在网上查了一下资料,了解到三者之间的使用难度与性能 三种爬虫方式的对比. 这样一比较我我选择了Lxml(xpa ...
- python2.7爬取豆瓣电影top250并写入到TXT,Excel,MySQL数据库
python2.7爬取豆瓣电影top250并分别写入到TXT,Excel,MySQL数据库 1.任务 爬取豆瓣电影top250 以txt文件保存 以Excel文档保存 将数据录入数据库 2.分析 电影 ...
- scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250
scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250 前言 经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo.这次我会以爬取豆瓣电影TOP250为例进一步为大 ...
- python 爬虫&爬取豆瓣电影top250
爬取豆瓣电影top250from urllib.request import * #导入所有的request,urllib相当于一个文件夹,用到它里面的方法requestfrom lxml impor ...
- 【转】爬取豆瓣电影top250提取电影分类进行数据分析
一.爬取网页,获取需要内容 我们今天要爬取的是豆瓣电影top250页面如下所示: 我们需要的是里面的电影分类,通过查看源代码观察可以分析出我们需要的东西.直接进入主题吧! 知道我们需要的内容在哪里了, ...
- Scrapy中用xpath/css爬取豆瓣电影Top250:解决403HTTP status code is not handled or not allowed
好吧,我又开始折腾豆瓣电影top250了,只是想试试各种方法,看看哪一种的方法效率是最好的,一直进行到这一步才知道 scrapy的强大,尤其是和selector结合之后,速度飞起.... 下面我就采用 ...
随机推荐
- matplotlib如何画子图
目录 前言 常用的两种方式 方式一:通过plt的subplot 方式二:通过figure的add_subplot 方式三:通过plt的subplots 如何不规则划分 前言 Matplotlib的可以 ...
- 算法将一个对象中的某一个key值变为true,其他值都为false
主要运用在,v-if v-show切换不同内容时,非常快的打开某一个区域,关闭其他的区域哈. 这样就不需要每一个设置false,打开区域设置为true. 可以优化代码哈 for in 主要循环对象(空 ...
- C++泛化动态数组
泛化动态数组 动态数组的核心思想是在存储数据时动态的管理数组元素占用的内存,通过调用动态数组的类方法来对数组中的数据进行增删改查操作.最初我们为数组申请10个元素的空间,放我们不断向数组中添加数据时, ...
- 基于Travis CI实现 Gitbook在 Github 和 Coding 的同步部署
前言 最近发现自己的博客在使用vpn的情况下打开很慢,百度站点也抓取失败,于是将自己的博客借助hexo-deploy 插件很容易同步部署到了coding上.只需要在你的hexo配置文件_config. ...
- codewars--js--the highest and lowest number + JS 字符串和数组相关知识
本文参考: http://blog.csdn.net/tyrionj/article/details/78653426 http://www.runoob.com/jsref/jsref-obj-st ...
- SVN状态图标不显示的解决办法
第一步:检查设置 右键->TortoiseSVN->setting->Icon Overlays->Status cache->default/Shell.或者 右键-& ...
- 搭建wordpress博客
环境说明 操作系统: CentOS 7.2 64位 1. 准备LAMP环境 LNMP 是 Linux.Nginx.MySQL 和 PHP 的缩写,是 WordPress 博客系统依赖的基础运行环境.我 ...
- SpringBoot图文教程6—SpringBoot中过滤器的使用
有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文系列教程技术大纲 鹿老师的Java笔记 SpringBo ...
- MySQL 8 复制
MySQL 8.0 支持的复制方法: 传统方法(基于二进制日志文件位置) 新方法(基于GTID) MySQL 8.0 支持的同步类型: 异步复制(内置) 同步复制(NDB集群) 半同步复制(半同步复制 ...
- C# WPF联系人列表(1/3)
微信公众号:Dotnet9,网站:Dotnet9,问题或建议:请网站留言, 如果对您有所帮助:欢迎赞赏. C# WPF联系人列表(1/3) 阅读导航 本文背景 代码实现 本文参考 1.本文背景 聊天软 ...