Summary of python standard library Beautiful Soup and MongoDb crawling Himalayan radio stations

Keywords: Python Windows xml Linux

The Beautiful Soup Standard Library is a Python library that extracts data from HTML/XML files. It enables you to navigate, find, and modify documents in your favorite converter, saving hours of work.The pymongo standard library is the bridge between the MongoDb NoSql database and the python language, through which data is saved to MongoDb.Use both to crawl data to Himalayan radio stations...

Beautiful Soup supports HTML parsers in Python standard libraries as well as some third-party parsers, one of which is lxml.This article uses lxml. For this installation, see Installation of python 3.6 lxml standard library lxml and use of etree
At the same time, this article uses XPath to parse what we want. For an introduction and use of XPath and Beautiful Soup, see Beautiful Soup 4.4.0 Document Introduction to XPath
The Beautiful Soup and XPath covered in this article are not very deep. I can understand them by looking at the official documentation, and I've added comments...
For pymongo standard libraries, I won't bother much. See pymongo module experience in python standard library

Sometimes, we need to determine the type of client that is currently making requests to the server, which is commonly referred to as User-Agent, or UA. The browser we use when browsing a web page is one of UA. In other words, UA is a browser. In HTTP protocol, the type of user browser, operating system, browser kernel and other information are described through the User-Agent request header.Identification.With this identification, websites you've visited can display different versions, providing a better experience for users or providing information statistics.Some websites formally use UA to prevent hackers or bored people like us from crawling to the site's data information.
Therefore, this code first lists all UA s to facilitate subsequent crawling.

Okay, here's what we're going to crawl for:

What we need is a link to the picture, alt, etc.

Then we click on the picture link to get the details inside. If some stations are multi-page, we use xpath to access them in turn.We also get the sound_id of the sound module from the album on the page...

The procedure is as follows:

import random
import requests
from bs4 import BeautifulSoup
import json
from lxml import etree
import pymongo


clients = pymongo.MongoClient("localhost", 27017)
db = clients["XiMaLaYa"]
collection_1 = db["album"]
collection_2 = db["detail"]

UA_LIST = [
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
    "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
    "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]
headers1 = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
    'Cache-Control': 'max-age=0',
    'Proxy-Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': random.choice(UA_LIST)  # User_agence Represents a user agent
}
headers2 = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
    'Cache-Control': 'max-age=0',
    'Proxy-Connection': 'keep-alive',
    'Referer': 'http://www.ximalaya.com/dq/all/2',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': random.choice(UA_LIST)
}


# The Beautiful library is used to process XML and HTML...
# The main purpose is to use BeautifulSoup module to process Html source code obtained by requests module
# Use lxml module to parse html source into tree structure, and xpath to process tree node.
def get_url():
    start_urls = ["http://www.ximalaya.com/dq/all/{}".format(num) for num in range(1,85)]
    # start_urls = ["http://www.ximalaya.com/dq/all/1"]
    for start_url in start_urls:
        html = requests.get(start_url, headers=headers1).text
        soup = BeautifulSoup(html, "lxml")  # Using lxml to process
        for item in soup.find_all(class_="albumfaceOutter"):  # Parse and find xml nodes
            content = {
                'href': item.a["href"],
                'title': item.img['alt'],
                'img_url': item.img['src']
            }
            collection_1.insert(content)
            # another(item.a["href"])
    print('Write Complete...')


# Go to the radio page http://www.ximalaya.com/15836959/album/303085 and process the paging recordings...
def another(url):
    html = requests.get(url, headers=headers1).text
    # /: means to select from the root node...
    # //: Indicates that the current node matching the selection selects the nodes in the document, regardless of their location...
    ifanother = etree.HTML(html).xpath('//div[@class="pagingBar_wrapper"]/a[last()-1]/@data-page')#Page link address ifanother is list type...
    if len(ifanother):  # Determine if a video recording is split into multiple pages...
        num = ifanother[0]  # Get the number of pages...
        print('This channel is saved in' + num + 'Pages')
        for n in range(1, int(num)):
            url2 = url + '?page={}'.format(n)
            get_m4a(url2)
        get_m4a(url)


# Get detailed data for the paged recording page...
def get_m4a(url):
    html = requests.get(url, headers=headers2).text
    numlist = etree.HTML(html).xpath('//div[@class="personal_body"]/@sound_ids')[0].split(',')
    for i in numlist:
        murl = 'http://www.ximalaya.com/tracks/{}.json'.format(i)
        html = requests.get(murl, headers=headers1).text
        dic = json.loads(html)
        collection_2.insert(dic)


if __name__ == "__main__":
    get_url()

Posted by daveyc on Thu, 13 Jun 2019 09:02:35 -0700