1. 程式人生 > >python爬蟲——爬取酷狗音樂top500(BeautifulSoup使用方法)

python爬蟲——爬取酷狗音樂top500(BeautifulSoup使用方法)

酷狗音樂Top500

進入,並按F12開啟開發者工具(本文以火狐瀏覽器為例)
這裡寫圖片描述

我們開始審查元素,在檢視器中觀察網頁原始碼,或者右鍵檢視頁面原始碼,看原始碼中是否有我們想要的資訊。這裡寫圖片描述
這裡寫圖片描述

我們可以在這裡看到歌單資訊,在ul標籤下正好有22條li個標籤,正好是頁面中的22首歌。因此我們只需獲取這些個li標籤,就能獲取酷狗top資訊。
這裡寫圖片描述
但這只是一頁資訊,我們看看第二頁是否也是如此!!!
這裡寫圖片描述
但是好像不能點選下一頁啊,需要我們下載客戶端。不要真的下載客戶端檢視,因為我們是程式設計師,哈哈!!!我們嘗試改一下網址資訊。
這裡寫圖片描述
我們發現這個辦法是真的可以,我們嘗試一下第三頁,第四頁,都能夠開啟。這樣們也找到了所有的網址。可以將500首全部遍歷出來。一共是23頁.
這裡寫圖片描述

我們已經將所有的需求全部分析出來了,接下來就是利用python獲取這些資訊。用到的模組有requests,BeautifulSoup,time。
只需少量的程式碼,便可實現我們的需求。我們先看程式碼

完整程式碼

import time
import requests
from bs4 import BeautifulSoup


headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:58.0) Gecko/20100101 Firefox/58.0'}


def top(url):
    html = requests.get(url, headers=headers)
    soup=BeautifulSoup(html.text,'lxml'
) No = soup.select('.pc_temp_num') titles = soup.select('.pc_temp_songname') href = soup.select('.pc_temp_songname') time = soup.select('.pc_temp_time') for No,titles,time,href in zip(No,titles,time,href): data={ 'NO':No.get_text().strip(), 'titles'
:titles.get_text(), 'time':time.get_text().strip(), 'href':href.get('href') } print(data) if __name__=='__main__': urls = {'http://www.kugou.com/yy/rank/home/{}-8888.html'.format(str(i)) for i in range(1,24)} for url in urls: time.sleep(5) top(url)

既然我們用到BeautifulSoup,我在這裡就簡單介紹一下這個模組。

BeautifulSoup

1.簡介

Beautiful Soup提供一些簡單的、python式的函式用來處理導航、搜尋、修改分析樹等功能。它是一個工具箱,通過解析文件為使用者提供需要抓取的資料,因為簡單,所以不需要多少程式碼就可以寫出一個完整的應用程式。Beautiful Soup自動將輸入文件轉換為Unicode編碼,輸出文件轉換為utf-8編碼。你不需要考慮編碼方式,除非文件沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然後,你僅僅需要說明一下原始編碼方式就可以了。
Beautiful Soup已成為和lxml、html6lib一樣出色的python直譯器,為使用者靈活地提供不同的解析策略或強勁的速度。

2.安裝

pip install BeautifulSoup4

easy_install BeautifulSoup4

3.建立BeautifulSoup物件
首先應該匯入BeautifulSoup類庫 from bs4 import BeautifulSoup
下面開始建立對像,在開始之前為了方便演示,先建立一個html文字,如下:

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

建立物件:soup=BeautifulSoup(html,’lxml’),這裡的lxml是解析的類庫,目前來說個人覺得最好的解析器了,一直在用這個,安裝方法:pip install lxml

Tag

Tag就是html中的一個標籤,用BeautifulSoup就能解析出來Tag的具體內容,具體的格式為soup.name,其中name是html下的標籤,具體例項如下:
print (soup.title) 輸出title標籤下的內容,包括此標籤,這個將會輸出
<title>The Dormouse's story</title>

注意:
這裡的格式只能獲取這些標籤的第一個,後面會講到獲取多個標籤的方法。其中對於Tag有兩個重要的屬性name和attrs,分別表示名字和屬性,介紹如下:
• name:對於Tag,它的name就是其本身,如soup.p.name就是p
• attrs是一個字典型別的,對應的是屬性-值,如print (soup.p.attrs),輸出的就是{‘class’: [‘title’], ‘name’: ‘dromouse’},當然你也可以得到具體的值,如
print (soup.p.attrs[‘class’]),輸出的就是[title]是一個列表的型別,因為一個屬性可能對應多個值,當然你也可以通過get方法得到屬性的,如:
print (soup.p.get(‘class’))。還可以直接使用print (soup.p[‘class’])

get

get方法用於得到標籤下的屬性值,注意這是一個重要的方法,在許多場合都能用到,比如你要得到<img src=”#”>標籤下的影象url,那麼就可以用soup.img.get(‘src’),具體解析如下:
print (soup.p.get("class")) 得到第一個p標籤下的src屬性

string

得到標籤下的文字內容,只有在此標籤下沒有子標籤,或者只有一個子標籤的情況下才能返回其中的內容,否則返回的是None具體例項如下:
print (soup.p.string) #在上面的一段文字中p標籤沒有子標籤,因此能夠正確返回文字的內容
print (soup.html.string) #這裡得到的就是None,因為這裡的html中有很多的子標籤

get_text()
可以獲得一個標籤中的所有文字內容,包括子孫節點的內容,這是最常用的方法

搜尋文件樹

find_all( name , attrs , recursive , text , **kwargs )

find_all是用於搜尋節點中所有符合過濾條件的節點

  • name引數:是Tag的名字,如p,div,title …..

soup.find_all("p") 查詢所有的p標籤,返回的是[<b>The Dormouse's story</b>],可以通過遍歷獲取每一個節點,如下:

ps=soup.find_all("p")
for p in ps:
    print p.get('class') 

得到p標籤下的class屬性
傳入正則表示式:soup.find_all(re.compile(r’^b’)查詢以b開頭的所有標籤,這裡的body和b標籤都會被查到
傳入類列表:如果傳入列表引數,BeautifulSoup會將與列表中任一元素匹配的內容返回.下面程式碼找到文件中所有<a>標籤和<b>標籤

soup.find_all(["a", "b"])
  • KeyWords引數,就是傳入屬性和對應的屬性值,或者一些其他的表示式

soup.find_all(id='link2'),這個將會搜尋找到所有的id屬性為link2的標籤。傳入正則表示式soup.find_all(href=re.compile("elsie")),這個將會查詢所有href屬性滿足正則表示式的標籤
傳入多個值:soup.find_all(id='link2',class_='title') ,這個將會查詢到同時滿足這兩個屬性的標籤,這裡的class必須用class_傳入引數,因為class是python中的關鍵詞
有些屬性不能通過以上方法直接搜尋,比如html5中的data-*屬性,不過可以通過attrs引數指定一個字典引數來搜尋包含特殊屬性的標籤,如下:

# [<div data-foo="value">foo!</div>]

data_soup.find_all(attrs={"data-foo": "value"}) #注意這裡的atts不僅能夠搜尋特殊屬性,亦可以搜尋普通屬性
soup.find_all("p",attrs={'class':'title','id':'value'})
相當與soup.find_all('p',class_='title',id='value')

  • text引數:通過 text 引數可以搜搜文件中的字串內容.與 name 引數的可選值一樣, text 引數接受 字串 , 正則表示式 , 列表, True
soup.find_all(text="Elsie")

[u'Elsie']

soup.find_all(text=["Tillie", "Elsie", "Lacie"])
[u'Elsie', u'Lacie', u'Tillie']
soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]
  • limit引數:find_all() 方法返回全部的搜尋結構,如果文件樹很大那麼搜尋會很慢.如果我們不需要全部結果,可以使用 limit引數限制返回結果的數量.效果與SQL中的limit關鍵字類似,當搜尋到的結果數量達到 limit 的限制時,就停止搜尋返回結果.

文件樹中有3個tag符合搜尋條件,但結果只返回了2個,因為我們限制了返回數量,程式碼如下:

soup.find_all("a", limit=2)
 [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
  • recursive 引數:呼叫tag的 find_all()方法時,BeautifulSoup會檢索當前tag的所有子孫節點,如果只想搜尋tag的直接子節點,可以使用引數recursive=False
    find( name , attrs , recursive , text , **kwargs )
    它與 find_all() 方法唯一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果,就是直接返回第一匹配到的元素,不是列表,不用遍歷,如soup.find("p").get("class")

通過標籤名查詢print (soup.select('title'))

[<title>The Dormouse's story</title>]
print (soup.select('a'))
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

通過類名查詢print (soup.select('.sister'))

[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

通過id名查詢print (soup.select('#link1'))

[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

組合查詢

學過 css 的都知道 css 選擇器,如 p #link1 是查詢 p 標籤下的 id 屬性為 link1 的標籤
print (soup.select('p #link1')) #查詢p標籤中內容為id屬性為link1的標籤

[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

print (soup.select("head > title")) #直接查詢子標籤

[<title>The Dormouse's story</title>]

屬性查詢

查詢時還可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標籤屬於同一節點,所以中間不能加空格,否則會無法匹配到。

print (soup.select('a[class="sister"]'))
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
print (soup.select('a[href="http://example.com/elsie"]'))
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

同樣,屬性仍然可以與上述查詢方式組合,不在同一節點的空格隔開,同一節點的不加空格,程式碼如下:

print (soup.select('p a[href="http://example.com/elsie"]'))
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

以上的 select 方法返回的結果都是列表形式,可以遍歷形式輸出,然後用 get_text() 方法來獲取它的內容

soup = BeautifulSoup(html, 'lxml')
print (type(soup.select('title')))
print (soup.select('title')[0].get_text())

for title in soup.select('title'):
    print (title.get_text())

以上就是BeautifulSoup的一些使用方法,看完BeautifulSoup的使用方法,我們就明白函式def top(url):中的用法了。在這個函式中,還有一個zip(No,titles,time,href),介紹一下
zip()
zip() 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。
如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同,利用 * 號操作符,可以將元組解壓為列表。
這裡寫圖片描述
這裡寫圖片描述

strip()
Python strip() 方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字元序列。
注意:該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。

執行結果:

這裡寫圖片描述

相關推薦

python爬蟲——音樂top500(BeautifulSoup使用方法)

酷狗音樂Top500 進入,並按F12開啟開發者工具(本文以火狐瀏覽器為例) 我們開始審查元素,在檢視器中觀察網頁原始碼,或者右鍵檢視頁面原始碼,看原始碼中是否有我們想要的資訊。 我們可以在這裡看到歌單資訊,在ul標籤下正好有22條li個標籤,

音樂Top500

TP pid 標準 html IT 行緩沖 瀏覽器 輕松 port 開發環境:windows環境+python3+requests庫(請求)+BeautifulSoup庫(解析) 目標:爬取酷狗音樂Top500並保存到txt中 整個案例源代碼: #導入程序需要的庫,req

Java爬蟲系列之實戰:音樂TOP500 的歌曲(附原始碼)

  在前面分享的兩篇隨筆中分別介紹了HttpClient和Jsoup以及簡單的程式碼案例: Java爬蟲系列二:使用HttpClient抓取頁面HTML Java爬蟲系列三:使用Jsoup解析HTML 今天就來實戰下,用他們來抓取酷狗音樂網上的 Top500排行榜音樂。接下來的程式碼

python音樂排行榜

rip idt clas strip pack 排行榜 upload 內容 nbsp 本文為大家分享了python爬取酷狗音樂排行榜的具體代碼,供大家參考,具體內容如下 python爬取酷狗音樂排行榜

java 爬蟲歌手資料

記錄防止忘記 包: jsoup-1.4.1 html解析 httpcore-4.0.1_1 httpclient-4.0.1 程式碼: 已經訪問的url佇列 //已經訪問連結佇列 public class VisitedUrlQueue { public static

筆記——用Requests庫和BeautifulSoup音樂資料

酷狗音樂top500榜單鏈接:http://www.kugou.com/yy/rank/home/1-8888.html觀察每頁的url,將第一頁url中home/後的1改成2,就恰好是第二頁的url。首先匯入相應的庫,同時設定好瀏覽器的header:import reque

音樂華語新歌榜前100

imp bs4 pan indexer quest 爬取 app gui 元素 import requests import time import lxml from bs4 import BeautifulSoup headers = { ‘User-Agen

[Python爬蟲]爬蟲例項:TOP500的資料

根據書籍《從零開始學Python網路爬蟲》P41,綜合案例2—爬取酷狗TOP500的資料修改而來. 使用模組requests和模組BeautifukSoup進行爬取. 不得不說,酷狗拿來跑爬蟲真是好,不ban不限制IP~ 要爬取的頁面資訊 酷狗TOP500 需要爬

爬蟲程式2-top500

爬取的內容為酷狗榜單中酷狗top500的音樂資訊,如圖所示。 網頁版酷狗不能手動翻頁,進行下一步的瀏覽。但通過觀察第一頁的URL: http://www.kugou.com/yy/rank/home/1-8888.html 這裡嘗試把數字1換為數字2,進行瀏覽,恰好返回的是第2頁的資訊(下圖)。進行

爬蟲入門,歌單top500,簡單爬蟲案例

import requests from bs4 import BeautifulSoup import time headers = { 'User-Agent': 'Mozilla/5.0

爬蟲入門5】TOP500

#coding utf-8 import time import requests from bs4 import BeautifulSoup class spider_KG_top500(object): def __init__(self):

scrapy爬蟲和Django後臺結合(音樂

程式碼結構:  Spider/spider/kuwo.py爬蟲程式碼: # -*- coding: utf-8 -*- import scrapy import demjson import re import os from ..items import Mus

PythonTOP100

import time import requests from bs4 import BeautifulSoup headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537

[python爬蟲]--豆瓣音樂topX

最近在學習python爬蟲,寫出來的一些爬蟲記錄在csdn部落格裡,同時備份一個放在了github上。 github地址:https://github.com/wjsaya/python_s

Python爬蟲-糗事百科段子

hasattr com ima .net header rfi star reason images 閑來無事,學學python爬蟲。 在正式學爬蟲前,簡單學習了下HTML和CSS,了解了網頁的基本結構後,更加快速入門。 1.獲取糗事百科url http://www.qiu

python爬蟲頁面源碼在本頁面展示

一個 nts ring 想要 strip code 空白 列表 ngs python爬蟲在爬取網頁內容時,需要將內容連同內容格式一同爬取過來,然後在自己的web頁面中顯示,自己的web頁面為django框架 首先定義一個變量html,變量值為一段HTML代碼 >&

python 爬蟲 證券之星網站

爬蟲 周末無聊,找點樂子。。。#coding:utf-8 import requests from bs4 import BeautifulSoup import random import time #抓取所需內容 user_agent = ["Mozilla/5.0 (Windows NT 10.0

python爬蟲海量病毒文件

tle format nbsp contex logs request spl tde __name__ 因為工作需要,需要做深度學習識別惡意二進制文件,所以爬一些資源。 # -*- coding: utf-8 -*- import requests import re

Python爬蟲廣州大學教務系統的成績(內網訪問)

enc 用途 css選擇器 狀態 csv文件 表格 area 加密 重要 用Python爬蟲爬取廣州大學教務系統的成績(內網訪問) 在進行爬取前,首先要了解: 1、什麽是CSS選擇器? 每一條css樣式定義由兩部分組成,形式如下: [code] 選擇器{樣式} [/code

python爬蟲——古詩詞

爬蟲 古詩詞 實現目標 1.古詩詞網站爬取唐詩宋詞 2.落地到本地數據庫頁面分析 通過firedebug進行頁面定位: 源碼定位: 根據lxml etree定位div標簽:# 通過 lxml進行頁面分析 response = etree.HTML(data