Python爬虫编程小案例

本文介绍了如何使用Python的aiohttp和lxml库,配合asyncio实现异步爬取一个歌词查找网站的46页数据,抓取每首歌的歌名、歌词等信息,并将它们保存为txt文件。
摘要由CSDN通过智能技术生成

偶然间发现一个通过歌词找歌曲的网站:https://www.91ge.cn/lxyyplay/find/ 目标:先抓取页面里的所有要查的歌词及歌名等信息,并存为txt文件

一共46页数据

网站截图如下:3364723b11a6f88606a72bdd656a182e.png抓取完整歌词数据,如下图:880a440718e50392baf59402c3b3c4d6.png源码如下:

import time
import aiohttp
from aiohttp import TCPConnector  # 处理ssl验证报错
from lxml import etree
import os
import asyncio

headers = {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}


# 返回每首歌的href函数
async def get_song_url(page_url):
    async with aiohttp.ClientSession(headers=headers, connector=TCPConnector(ssl=False)) as session:
        async with session.get(page_url) as res:
            html = await res.text()
            tree = etree.HTML(html)
            url_lst = tree.xpath('//div[@class="des"]/a/@href')
    return url_lst


# 获取每首歌的详细信息
async def get_song_word(song_url):
    async with aiohttp.ClientSession(headers=headers, connector=TCPConnector(ssl=False)) as session:
        async with session.get(song_url) as res:
            html = await res.text()
            tree = etree.HTML(html)
            if tree is not None:
                song_question = tree.xpath('//div[@class="logbox"]')
                if song_question:
                    song_q = song_question[0].xpath('./h1/text()')[0]
                else:
                    pass
                div_word = tree.xpath('//div[@class="logcon"]')
                if div_word:
                    where_song = div_word[0].xpath('./h2[1]/text()')[0]
                    question_song = div_word[0].xpath('./p[1]/text()')[0]
                    answer_song = div_word[0].xpath('./p[2]/text()')[0]
                    song_words = div_word[0].xpath('./p[position()>2]//text()')
                    # song_name = div_word.xpath('./h2[2]/text()')[0].strip('\r\n\t')
                    song_words = ''.join(song_words[:-1]).strip('\r\n\t')

                    with open(f'songs/{song_q}.txt', 'w') as f:
                        f.write(where_song + '\n' + question_song + '\n' + answer_song + '\n\n' + song_words)
            else:
                pass


if __name__ == '__main__':
    t1 = time.time()
    if not os.path.exists('songs'):
        os.makedirs('songs')
        loop = asyncio.get_event_loop()
        for n in range(1, 47):
            song_url = f'https://www.91ge.cn/lxyyplay/find/list_16_{n}.html'
            urls = loop.run_until_complete(get_song_url(song_url))
            tasks = [get_song_word(url) for url in urls]
            loop.run_until_complete(asyncio.gather(*tasks))

        print(f'耗时:{time.time() - t1:.2f}秒')
    else:
        song_word = input('请输入要查找的歌词: ')
        song_lst = os.listdir('songs')

        for song in song_lst:
            if song_word in song:
                with open(os.path.join('songs', song), 'r') as f:
                    print(f.read())
                break
        else:
            print('no found')

运行结果如下图:69fc387cc376ed67f7f233aea3e7163f.png此案例到的所有模块及函数的相关知识可以通过小蜜蜂AI的GPT得到更多的详细回答。小蜜蜂AI网址:https://zglg.work。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值