详解如何用Python写个听小说的爬虫
作者:派森酱 时间:2021-09-04 09:56:09
在路上发现好多人都喜欢用耳机听小说,同事居然可以一整天的带着一只耳机听小说。小编表示非常的震惊。今天就用 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。
肯定是少了关键性的参数,回到上面 Network 仔细观察 mp3 的 url,发现在 url 后面带了一个 key 的关键字。如下图,这个 key 是来自于 https://img.tingchina.com/play/h5_jsonp.asp?0.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()
完整代码
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
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)
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:]
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()
来源:https://mp.weixin.qq.com/s/JzzHwQ0G9IoenlmdEXi3hA
标签:Python,爬虫,小说
0
投稿
猜你喜欢
python包和文件夹有的区别点总结
2022-05-09 11:59:01
Selenium之模拟登录铁路12306的示例代码
2022-01-22 17:06:27
Python根据当前日期取去年同星期日期
2021-09-14 15:01:48
Python socket网络编程TCP/IP服务器与客户端通信
2023-09-13 01:46:02
用python写一个windows下的定时关机脚本(推荐)
2022-03-01 10:26:37
启发式评估(heuristic evaluation)
2009-08-27 13:03:00
详解css定位与定位应用
2007-05-11 16:52:00
python中数字列表转化为数字字符串的实例代码
2021-04-30 02:46:45
Python压缩和解压缩zip文件
2023-09-16 21:20:10
python 字符串和整数的转换方法
2023-10-11 02:31:42
django将网络中的图片,保存成model中的ImageField的实例
2023-12-23 01:11:33
python udp如何实现同时收发信息
2023-12-16 10:06:33
python中enumerate函数遍历元素用法分析
2021-08-07 10:07:18
好用的JS图片预加载类
2007-08-13 13:49:00
Python实现的读取/更改/写入xml文件操作示例
2023-06-05 05:16:42
巧用Dreamweaver MX设计导航栏特效
2009-07-10 13:17:00
Python利用redis-py实现集合与有序集合的常用指令操作
2021-02-11 21:29:24
Python中通过@classmethod 实现多态的示例
2021-02-25 06:10:33
对Keras自带Loss Function的深入研究
2021-08-27 03:18:24
Python中itertools的用法详解
2022-06-05 13:34:52