實(shí)習(xí)

入職第二天

用爬蟲爬取網(wǎng)站音頻數(shù)據(jù)

昨天是 入職第一天,晚上要下載數(shù)據(jù),又玩了一會(huì),有點(diǎn)累,沒有寫總結(jié),今天上班的時(shí)候摸摸魚,補(bǔ)上。

現(xiàn)在小公司都不帶實(shí)習(xí)生的嗎,上來就讓干活。。。。有個(gè)聲音的項(xiàng)目比較緊,所以第一天的任務(wù)是給我一個(gè)網(wǎng)站,搜集建筑工地的各種聲音。幸好之前學(xué)過一些爬蟲,用爬蟲技術(shù)批量下載了建筑施工的一批數(shù)據(jù),大約有14000多條,4.5G左右。

分享一下自己是如何做的:

用了最原始的爬蟲技術(shù):
# coding : utf-8
import socket
import re
import os
import ssl
from urllib.request import urlopen, Request, urlretrieve

socket.setdefaulttimeout(100)
ssl._create_default_https_context = ssl._create_unverified_context
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}


def create_file(key_words):
    if os.path.isdir(key_words):
        pass
    else:
        os.mkdir(key_words)


def getHtml(url):
    page = urlopen(url)
    html = page.read().decode('utf-8')
    return html


def getPage(html):
    pat = '''title="Last Page">(.*?)</a></li><p class="number_of_results">'''
    page_list = re.compile(pat).findall(html)
    return int(page_list[0])


def getVoice(html):
    x = 0
    ls = []
    pat = '''<a class="mp3_file" href="(.*?)" title="mp3 file">'''
    voicelist = re.compile(pat).findall(html)
    for voiceurl in voicelist:
        x += 1
        voiceurl = 'https://freesound.org' + voiceurl
        ls.append(voiceurl)
    return ls


def downloadvoice(url_list, key_words, count):
    x = count
    for i in url_list:
        try:
            urlretrieve(i, key_words+'/%s.mp3' % x)
            print("音頻%s下載成功" % x)
            x += 1
        except:
            print("音頻%s下載失敗" % x)
            x += 1


if __name__ == '__main__':
    ls = []
    key_words = "mechanical_engine"
    create_file(key_words)
    html = getHtml('https://freesound.org/search/?q=' + key_words + '&page=1')
    page_number = getPage(html)
    print(page_number)
    for i in range(1, page_number):
        html = getHtml('https://freesound.org/search/?q=' + key_words + '&page=' + str(i))
        #page_number = getPage(html)
        #ls = getVoice(html, page_number)
        ls = getVoice(html)
        #print(ls)
        downloadvoice(ls, key_words, i * 15)

昨天用自己電腦跑了一夜,發(fā)現(xiàn)有重復(fù)的。。。無語,自己太菜了。

今天只能整改了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容