Python爬虫实战(3)-爬取豆瓣音乐Top250数据(超详细)


###前言
首先我们先来回忆一下上两篇爬虫实战文章:

第一篇:讲到了requests和bs4和一些网页基本操作,第二篇:用到了正则表达式-re模块。

今天我们用lxml库和xpath语法来爬虫实战。

1.安装lxml库

window:直接用pip去安装,注意一定要找到pip的安装路径

1
pip install lxml

2.xpath语法

xpath语法不会的可以参考下面的地址:

http://www.w3school.com.cn/xpath/index.asp

爬虫实战

先上部分效果图:

image

今天我们来爬一下“豆瓣音乐Top250的数据”

1.观察网页切换规律

https://music.douban.com/top250?start=0

https://music.douban.com/top250?start=25

https://music.douban.com/top250?start=50

从中我们已发现了规律。

2.爬取豆瓣音乐中的歌名、信息、星评 爬虫完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import  requests
from  lxml import  etree
headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
list=[1]
def getResult():
   urls=["https://music.douban.com/top250?start={}".format(str(i)) for i in  range(0,250,25)]
   for url in  urls:
       data = requests.get(url, headers=headers)
       html = etree.HTML(data.text)
       #循环标签
       count = html.xpath("//tr[@class='item']")
       for info in count:
           title = info.xpath("normalize-space(td[2]/div/a/text())")#标题
           list[0]=title #因为title用normalize-space去掉空格了,再生产result时标题显示不全,所以我用了list替换它
           star = info.xpath("td[2]/div/div/span[2]/text()")  # 星评
           brief_introduction = info.xpath("td[2]/div/p//text()"#简介
           #生成result串
           for star, title, brief_introduction in zip(star, list, brief_introduction):
               result = {
                   "title": title,
                   "star": star,
                   "brief_introduction": brief_introduction,
               }
               print(result)
if __name__ == '__main__':
   getResult()

分析:

  • 代码中urls为了循环出所有的url

  • 对xpath不懂的可以去看一下具体的语言,还是比较简单明了的,而且使用非常方便

  • normalize-space表示通过去掉前导和尾随空白并使用单个空格替换一系列空白字符,使空白标准化。如果省略了该参数,上下文节点的字符串值将标准化并返回

基本上就是这些难点,大家有不会的可以直接问我,另外大家也可以尝试去爬取别的数据,多敲多练!

希望对刚入门的朋友有所帮助!

秦子帅 wechat
欢迎您扫一扫上面的微信公众号,带你走进Android、Python技术!
坚持原创技术分享,您的支持将鼓励我继续创作!