python爬取酷狗音乐排行榜

yipeiwu_com6年前Python爬虫

本文为大家分享了python爬取酷狗音乐排行榜的具体代码,供大家参考,具体内容如下

#coding=utf-8
from pymongo import MongoClient
import time 
import requests 
from lxml import etree 
 
client = MongoClient()      #连接mongo
hello = client.hello       #连接数据库
user = hello.song         #连接表
 
headers = { 
  'User-Agent': 'Mozilla/5.0 (Android 6.0; Nexus 5 Build/MRA58N)\
  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Mobile Safari/537.36'} 
 
def get_info(url): 
  '''
  get源码,encode,解析,xpath,保存 
  '''
  response = requests.get(url, headers=headers) 
  response = response.text.encode('utf-8') 
  selector = etree.HTML(response) 
  soup = selector.xpath('//*[@class="pc_temp_songlist "]/ul//li/a/text()') 
 
  #保存到本地
  # with open('aa.txt','a') as f:
    # for i in soup:
      # f.write(i.encode('utf-8') + '\n')
 
  #存入数据库
  for i in soup:
    user.insert({'song': i})
 
if __name__ == '__main__': 
  urls = ['http://www.kugou.com/yy/rank/home/{}-8888.html?from=rank'.format(str(i)) for i in range(1, 24)] 
  for url in urls: 
    print(url) 
    get_info(url)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

利用Python3分析sitemap.xml并抓取导出全站链接详解

利用Python3分析sitemap.xml并抓取导出全站链接详解

前言 最近网站从HTTPS转为HTTP,更换了网址,旧网址做了301重定向,折腾有点大,于是在百度站长平台提交网址,不管是主动推送还是手动提交,前提都是要整理网站的链接,手动添加太麻烦,...

python3爬虫怎样构建请求header

python3爬虫怎样构建请求header

写一个爬虫首先就是学会设置请求头header,这样才可以伪装成浏览器。下面小编我就来给大家简单分析一下python3怎样构建一个爬虫的请求头header。 1、python3跟2有了细微...

Python多线程爬虫简单示例

 python是支持多线程的,主要是通过thread和threading这两个模块来实现的。thread模块是比较底层的模块,threading模块是对thread做了一些包装...

python+mongodb数据抓取详细介绍

分享点干货!!! Python数据抓取分析 编程模块:requests,lxml,pymongo,time,BeautifulSoup 首先获取所有产品的分类网址: def s...

Python3 实现爬取网站下所有URL方式

获取首页元素信息: 目标 test_URL:http://www.xxx.com.cn/ 首先检查元素,a 标签下是我们需要爬取得链接,通过获取链接路径,定位出我们需要的信息 sou...