吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 7627|回复: 21
收起左侧

[Python 原创] 【python】爬取并批量下载网易云歌单,嗨翻暑假!

[复制链接]
朕灬黑手党 发表于 2018-7-6 15:10
本帖最后由 wushaominkk 于 2018-7-6 15:21 编辑

昨天发布了一个爬取猫眼Top100电影的爬虫,暑假够你看电影的啦!
传送门:https://www.52pojie.cn/thread-761783-1-1.html
还是有那么一丢丢成就感
今天给你们带来一个批量下载网易云歌单歌曲的Demo. 不能下载会员的!

我优化了一下我的代码.昨天被人说直接放代码没看懂,今天我给你分下一下我的代码和思路!
喜欢直接码字,不注意格式了!这是我第二次发爬虫帖子,分享一下心得!


首先导入一下包
[Python] 纯文本查看 复制代码
import requests
import time
from multiprocessing import Pool
from bs4 import BeautifulSoup
from urllib.request import urlretrieve


#1.获取页面源代码   url =  https://music.163.com/#/playlist?id=2269661190  注意:你在敲代码时候,需要去掉原来连接里面的 /#
附上代码:
[Python] 纯文本查看 复制代码
#1.获取页面源代码
def get_page():
    """获取网页源代码(选择自己喜欢的网易云歌单连接)"""
    # 去掉原链接里面的   #/
    url ="https://music.163.com/playlist?id=2269661190"
    #请求头
    headers ={
        'Host':'music.163.com',
        'Referer':'https://music.163.com/',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
    }
    #获取网页源代码
    res = requests.get(url,headers=headers).text
    #创建对象  解析网页
    r = BeautifulSoup(res,"html.parser")

#2.获取ID
    music_dict = {}
    #找源代码中的a标签
    result = r.find("ul",{'class':'f-hide'}).find_all('a')
    for music in result:
        music_id = music.get('href').strip("/song?id=")#去掉/song?id
        music_name = music.text #获取其中的文字
        music_dict[music_id] = music_name
    return music_dict

这个函数目的是为了获取每个歌的ID地址,具体的看图片
这里最后有个return  是为了给下面一个函数传入参数的

然后我们获取了想要的ID
然后就下载!!!!!
使用了  from urllib.request import urlretrieve
里面urlretrive(url,path)
源码:
[Python] 纯文本查看 复制代码
#3.下载歌曲
def download_song(music_dict):
    """下载音乐"""
    for song_id in music_dict:
        song_url = "http://music.163.com/song/media/outer/url?id=%s.mp3"%song_id
        #下载地址(地址填写自己的地址)
        path="C:\\Users\Administrator\Desktop\网易云音乐\\%s.mp3"%music_dict[song_id]#通过键值对来查找歌曲名字
        #下载音乐  urlretriver (地址  路径)
        time.sleep(1)
        urlretrieve(song_url,path)
        print("正在下载%s"%music_dict[song_id])


好了 上面就是很简单的过程, 放上全部源码!!
[Python] 纯文本查看 复制代码
#!/usr/bin/env python#!--*--coding:utf-8 --*--
#![url=home.php?mod=space&uid=238618]@Time[/url]    :2018/7/6 12:13
#![url=home.php?mod=space&uid=686208]@AuThor[/url]   TrueNewBee
#爬取并批量下载网易云歌单歌曲
#根据URL下载音乐  [url=https://music.163.com/#/playlist?id=2269661190]https://music.163.com/#/playlist?id=2269661190[/url]

import requests
import time
from multiprocessing import Pool
from bs4 import BeautifulSoup
from urllib.request import urlretrieve


#1.获取页面源代码
def get_page():
    """获取网页源代码(选择自己喜欢的网易云歌单连接)"""
    # 去掉原链接里面的   #/
    url ="https://music.163.com/playlist?id=2269661190"
    #请求头
    headers ={
        'Host':'music.163.com',
        'Referer':'https://music.163.com/',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
    }
    #获取网页源代码
    res = requests.get(url,headers=headers).text
    #创建对象  解析网页
    r = BeautifulSoup(res,"html.parser")

#2.获取ID
    music_dict = {}
    #找源代码中的a标签
    result = r.find("ul",{'class':'f-hide'}).find_all('a')
    for music in result:
        music_id = music.get('href').strip("/song?id=")#去掉/song?id
        music_name = music.text #获取其中的文字
        music_dict[music_id] = music_name
    return music_dict


#3.下载歌曲
def download_song(music_dict):
    """下载音乐"""
    for song_id in music_dict:
        song_url = "http://music.163.com/song/media/outer/url?id=%s.mp3"%song_id   #网易云音乐的外链
        #下载地址(地址填写自己的地址)
        path="C:\\Users\Administrator\Desktop\网易云音乐\\%s.mp3"%music_dict[song_id]#通过键值对来查找歌曲名字
        #下载音乐  urlretriver (地址  路径)
        time.sleep(1)
        urlretrieve(song_url,path)
        print("正在下载%s"%music_dict[song_id])


def  main():
    music_dict =get_page()
    download_song(music_dict)

if __name__ == '__main__':
    main()




评分热心免费!!!  附上源码地址:https://github.com/TrueNewBee/pythonDemo
有不懂得可以留言评论,以后有机会出更详细教程


QQ截图20180706131807.png
这个是网易云歌曲ID
5TR[9VEF`}`%)GNI84]JAVG.jpg

点评

用这个url只能获取1000首歌曲,建议研究下http://music.163.com/weapi/v3/playlist/detail。需要用到aes加密  发表于 2018-7-10 09:30

免费评分

参与人数 9吾爱币 +10 热心值 +8 收起 理由
tymon42 + 1 谢谢@Thanks!
月明风兮 + 1 + 1 谢谢@Thanks!
那边 + 1 我很赞同!
雪莱鸟 + 1 + 1 用心讨论,共获提升!
jshon + 1 + 1 谢谢@Thanks!
gxweb + 1 + 1 谢谢@Thanks!
删掉丶关于n1 + 1 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
Chacker + 1 + 1 我很赞同!
wushaominkk + 3 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

wazz129 发表于 2018-7-6 23:40
wazz129 发表于 2018-7-6 23:24
这是我 爬淘宝的利用selenium 自动打开 并保存到你自己的数据库 mogodb  转换成csv  或者txt格式 记得转换 ...

忘记了  刚开始看Django  弄了个投票  搜索字数  俩个.搜索字数是   看note.md  有惊喜哦   https://github.com/then-on/WX
wazz129 发表于 2018-7-6 23:24
这是我 爬淘宝的利用selenium 自动打开 并保存到你自己的数据库 mogodb  转换成csv  或者txt格式 记得转换啊
[Python] 纯文本查看 复制代码
# 利用 Selenium 抓取淘宝商品并用 PyQuery 解析得到商品的图片、名称、价格、购买人数、
# 店铺名称、店铺所在地信息,并将其保存到MongoDB。  以及数据库,csv格式等

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote
browser = webdriver.Chrome()
wait = WebDriverWait(browser,10)

KEYWORD = input('请输入要检索的物品:')

def index_page(page):
    """
    抓取索引页
    :param page:页码
    :return:
    """
    print('正在爬取第',page,'页')
    try:
        url = 'https://s.taobao.com/search?q=' + quote(KEYWORD)
        browser.get(url)
        if page > 1:
            input = wait.until(
                 EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager div.form > input'))
            )

            submit = wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager div.form > span.btn.J_Submit'))
            )
            input.clear()
            input.send_keys(page)
            submit.click()
        wait.until(
            EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'), str(page))
        )
        wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item'))
        )
        get_products()
    except TimeoutException:
        index_page(page)

from pyquery import PyQuery as pq
def get_products():
    """
    提交商品数据
    :return:
    """
    html = browser.page_source
    doc = pq(html)
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        product = {
            'image':item.find('.pic .img').attr('data-src'),
            'price':item.find('.price ').text(),
            'deal':item.find('.deal-cnt').text(),
            'title':item.find('.title').text(),
            'shop':item.find('.shop').text(),
            'location':item.find('.location').text(),
        }
        print(product)
        write_txt(product)
        save_mysql(product)
        save_to_mongo(product)
        save_image(product)

import os
from hashlib import md5
import requests
def save_image(item):
    if not os.path.exists(item.get('shop')):
        os.mkdir(item.get('shop'))
        try:
            local_image_url = item.get('image')
            response = requests.get('http:' + local_image_url)
            file_path = '{0}/{1}.{2}'.format(item.get('shop'),md5(response.content).hexdigest(),'jpg')
            if not os.path.exists(file_path):
                with open(file_path,'wb') as f:
                    f.write(response.content)
                    print('Success to Save image')
            else:
                print('Already Downloaded', file_path)
        except requests.ConnectionError:
            print('Failed to Save Image')


import pymongo
MONGO_URL = '127.0.0.1'
MONGO_DB = 'taobao'
MONGO_COLLECTION = 'products'
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]
def save_to_mongo(result):
    """
    保存到Mongodb 名字淘宝
    :return:结果
    """
    try:
        if db[MONGO_COLLECTION].insert(result):
            print('存储到Mongodb成功')
    except Exception:
        print('存储到Mongodb失败')

def write_txt(content):
    try:
        with open('tao.csv','a',encoding='utf-8') as f:
            f.write(str(content)+ '\n') #要存到txt,csv 字典格式不能直接写入 转换成json  或者 字符串
            print('写入成功')
    except Exception:
        print('写入失败')

import pymysql
sql_db = pymysql.connect(host = 'localhost',user = 'root',password = 'root123',port = 3306,db = 'tao',charset='utf8')
cursor = sql_db.cursor()
def save_mysql(content):
    table = 'ipad'
    keys = ','.join(content.keys())
    values = ','.join(['%s'] * len(content))
    sql = 'insert into {table}({keys}) values ({values})'.format(table=table,keys=keys,values=values)
    try:
        if cursor.execute(sql,tuple(content.values())):
            print('Successful')
            sql_db.commit()
    except:
        print('Failed')
        sql_db.rollback()
    #sql_db.close()


def main():
    """
    遍历每一页
    :return:
    """
    MAX_PAGE = input("MAX_PAGE:")
    MAX_PAGE = int(MAX_PAGE)
    for i in range(1,MAX_PAGE+1):
        index_page(i)
    browser.close()
if __name__ == '__main__':
    main()
五月何欢 发表于 2018-7-6 15:13
是批量获取吗?我有一个免费下载全站音乐的站点,能添加进去规则么?这样可以实现全网的音乐。
wushaominkk 发表于 2018-7-6 15:20
发帖前,看看版规,注意标题规范,已帮你修改好了,下次注意!
 楼主| 朕灬黑手党 发表于 2018-7-6 15:33
wushaominkk 发表于 2018-7-6 15:20
发帖前,看看版规,注意标题规范,已帮你修改好了,下次注意!

好的!新人发帖,下次注意!
 楼主| 朕灬黑手党 发表于 2018-7-6 15:35
五月何欢 发表于 2018-7-6 15:13
是批量获取吗?我有一个免费下载全站音乐的站点,能添加进去规则么?这样可以实现全网的音乐。

这个仅仅是个1.0,你可以进行迭代!
小彭彭 发表于 2018-7-6 15:35
for循环建议换多进程
 楼主| 朕灬黑手党 发表于 2018-7-6 15:41
小彭彭 发表于 2018-7-6 15:35
for循环建议换多进程

可以迭代,多进程学的有点不大好,目前继续python学习!
吾爱男人 发表于 2018-7-6 15:50
需要VIP的都能下载吗?
pjext 发表于 2018-7-6 15:51
技术好贴,赞一个
jshon 发表于 2018-7-6 15:54
说实话,感觉用处不是很大,但很佩服楼主的钻研精神
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-21 18:59

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表