[python爬蟲]--爬取豆瓣音樂topX
阿新 • • 發佈:2019-02-15
最近在學習python爬蟲,寫出來的一些爬蟲記錄在csdn部落格裡,同時備份一個放在了github上。
github地址:https://github.com/wjsaya/python_spider_learn/
本次內容:從豆瓣的top250音樂介面爬取指定的topX專輯。
思路:
- 拼接出豆瓣topX頁面URL。
- 用BS去訪問和解析豆瓣topX頁面URL,獲取頁面內的所有歌手名和專輯名並拼接,然後輸出。
程式碼:
#coding: utf-8
import re
import requests
from bs4 import BeautifulSoup
url = "https://music.douban.com/top250?start=25"
firefox={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0 FirePHP/0.7.4"}
def main():
#主函式,一切的開始,以及變數值獲取
maxm = input("想獲取豆瓣排名前多少的音樂列表呢?(0-250之間):")
count_main = 0
url_li = get_pages()
for i in range(0,9):
if count_main < int(maxm):
count_main += get_details(url_li[i], count_main, maxm)
def get_soup(url):
#獲取html並解析為BS
html = requests.get(url, headers=firefox)
soup = BeautifulSoup(html.content, 'lxml')
return soup
def get_details(url, count_in_loop, maxm):
#獲取豆瓣音樂專輯的名稱與url連結
content = get_soup(url)
html = content.find_all('a', class_="nbg")
for i in range(0,25 ):
if count_in_loop < int(maxm):
print ("歌手-名字:"+html[i]["title"])
print ("連結:"+html[i]["href"])
count_in_loop += 1
return count_in_loop
def get_pages():
#從豆瓣網頁解析出豆瓣下方的下一頁標籤中的地址列表,此函式可升級為解析下一頁url。
#或者直接構造豆瓣url地址,?start=XXX即可。
content = get_soup(url)
l = content.find("div", class_="paginator")
url_li = []
for i in l.find_all('a'):
url_li.append(i['href'])
return url_li[0:9]
if __name__ == '__main__':
main()