用 50 行代码写个听小说的爬虫

在路上发现好多人都喜欢用耳机听小说,同事居然可以一整天的带着一只耳机听小说。

今天就用 Python 下载听小说 tingchina.com 的音频。

书名和章节列表

随机点开一本书,这个页面可以使用 BeautifulSoup 获取书名和所有单个章节音频的列表。复制浏览器的地址,如:https://www.tingchina.com/yousheng/disp_31086.htm

from bs4 import BeautifulSoup
import requests
import re
import random
import os

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}

def get_detail_urls(url):
    url_list = []
    response = requests.get(url, headers=headers)
    response.encoding = 'gbk'
    soup = BeautifulSoup(response.text, 'lxml')
    name = soup.select('.red12')[0].strong.text
    if not os.path.exists(name):
        os.makedirs(name)
    div_list = soup.select('div.list a')
    for item in div_list:
        url_list.append({'name': item.string, 'url': 'https://www.tingchina.com/yousheng/{}'.format(item['href'])})
    return name, url_list


打开单个章节的链接,在 Elements 面板用章节名称作为搜索词,在底部发现了一个 script,这一部分就是声源的地址。

音频地址

在 Network 面板可以看到,声源的 url 域名和章节列表的域名是不一样的。在获取下载链接的时候需要注意这一点。

def get_mp3_path(url):
    response = requests.get(url, headers=headers)
    response.encoding = 'gbk'
    soup = BeautifulSoup(response.text, 'lxml')
    script_text = soup.select('script')[-1].string
    fileUrl_search = re.search('fileUrl= "(.*?)";', script_text, re.S)
    if fileUrl_search:
        return 'https://t3344.tingchina.com' + fileUrl_search.group(1)


惊喜总是突如其来,把这个 https://t3344.tingchina.com/xxxx.mp3 放入浏览器中运行居然是 404。

如果你对学习python感兴趣,可以加入这个大家庭:347304177,我们一起学习,有多种python教程和视频录屏可以自己下载。

下载

肯定是少了关键性的参数,回到上面 Network 仔细观察 mp3 的 url,发现在 url 后面带了一个 key 的关键字。如下图,这个 key 是来自于 https://img.tingchina.com/play/h5_jsonp.asp0.5078556568562795 的返回值,可以使用正则表达式将 key 取出来。

def get_key(url):
    url = 'https://img.tingchina.com/play/h5_jsonp.asp?{}'.format(str(random.random()))
    headers['referer'] = url
    response = requests.get(url, headers=headers)
    matched = re.search('(key=.*?)";', response.text, re.S)
    if matched:
        temp = matched.group(1)
        return temp[len(temp)-42:]

最后的最后在 __main__ 中将以上的代码串联起来。

if __name__ == "__main__":
    url = input("请输入浏览器书页的地址:")
    dir,url_list = get_detail_urls()

    for item in url_list:
        audio_url = get_mp3_path(item['url'])
        key = get_key(item['url'])
        audio_url = audio_url + '?key=' + key
        headers['referer'] = item['url']
        r = requests.get(audio_url, headers=headers,stream=True)
        with open(os.path.join(dir, item['name']),'ab') as f:
            f.write(r.content)
            f.flush()

总结

这个 Python 爬虫比较简单,每个月 30 元的流量都不够用,有了这个小程序在地铁上就可以不用流量听小说了。

示例代码:(https://github.com/JustDoPython/pythonexamples/tree/master/moumoubaimifan/tingbook)

<think>好的,用户想用Python小说爬虫,需要教程或示例代码。首先,我需要整理现有的引用内容,看看哪些信息能帮到他。 根据用户提供的引用,特别是引用[2]、[3]、[4],里面提到了爬虫的基本流程、常用库如Requests和BeautifulSoup,以及示例代码。引用[4]中的代码片段显示如何通过查找特定的div和属性来定位小说内容,这可能有用。 用户可能需要一个基础的教程步骤,从安装库开始,到发送请求、解析HTML、提取数据,最后保存结果。需要确保步骤清晰,代码示例正确,并且提醒注意事项,比如遵守网站规则和设置延迟。 还要注意用户提到的系统级指令,比如数学公式的格式,但这个问题可能不涉及数学内容,所以暂时不用处理。但需要检查是否有其他格式要求,比如代码块的使用是否正确。 另外,用户希望生成相关问题,可能需要包括处理动态页面、错误处理、优化方法等,这些在引用[2]和[3]中都有提到,比如使用Selenium处理JavaScript,或者异常处理。 需要确保回答结构清晰,分步骤讲解,代码示例正确,并且引用正确来源。同时,要避免使用Markdown格式,但根据用户提供的示例,代码块应该是用三个反引号包裹的,所以需要保留代码块的格式。 最后,检查是否有遗漏的部分,比如免责声明和遵守robots.txt,这些在引用[2]和[3]中都有提到,应该包含在注意事项里。</think>根据提供的参考资料,我将分步骤说明如何使用Python小说爬虫,并提供关键代码示例: ### 一、基础爬虫实现流程 1. **安装依赖库** ```python pip install requests beautifulsoup4 ``` 2. **发送HTTP请求** ```python import requests url = "https://novel.example.com/book123" headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(url, headers=headers) ``` 3. **解析HTML内容** ```python from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') ``` 4. **提取章节数据** ```python chapters = [] for item in soup.find_all('div', class_='chapter-list'): title = item.find('a').text.strip() link = item.find('a')['href'] chapters.append({'title': title, 'link': link}) ``` 5. **内容保存** ```python with open('novel.txt', 'w', encoding='utf-8') as f: for chap in chapters: f.write(f"{chap['title']}\n{chap['content']}\n\n") ``` ### 二、处理动态加载内容 对于JavaScript渲染的页面,推荐使用Selenium方案: ```python from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Chrome() driver.get(url) soup = BeautifulSoup(driver.page_source, 'html.parser') # 后续解析逻辑与静态页面相同 ``` ### 三、完整示例代码 ```python import requests from bs4 import BeautifulSoup import time def get_novel_content(base_url): # 获取目录页 index_res = requests.get(base_url) soup = BeautifulSoup(index_res.text, 'html.parser') # 提取章节链接 chapters = [] for link in soup.select('.chapter-list a'): chapters.append({ 'title': link.text, 'url': urljoin(base_url, link['href']) }) # 遍历章节下载内容 for chap in chapters[:5]: # 示例仅下载前5章 chap_res = requests.get(chap['url']) chap_soup = BeautifulSoup(chap_res.text, 'html.parser') content = chap_soup.find('div', class_='content').text chap['content'] = content time.sleep(1) # 遵守爬虫礼仪 return chapters ``` ### 四、注意事项 1. 遵守目标网站`robots.txt`协议[^2] 2. 添加请求头模拟浏览器访问 3. 设置合理请求间隔(建议2-5秒) 4. 处理异常状态码(404、503等) 5. 注意网站反爬机制(验证码、IP封锁)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值