转载本文请联系Python技术公众号。在路上,我发现很多人都喜欢戴着耳机听小说,而我的同事居然可以整天戴着耳机听小说。小编表示非常震惊。今天用Python下载并收听小说tingchina.com的音频。书名和章节列表随机点击一本书,该页面可以使用BeautifulSoup获取书名和所有单章音频列表。复制浏览器地址,如:https://www.tingchina.com/yousheng/disp_31086.htm。frombs4importBeautifulSoupimportrequestsimportreimportrandomimportosheaders={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/91.0.4472.114Safari/537.36'}defget_detail_url.get(urlquest)=urls,headers=headers)response.encoding='gbk'soup=BeautifulSoup(response.text,'lxml')name=soup.select('.red12')[0].strong.textifnotos.path.exists(名称):os.makedirs(name)div_list=soup.select('div.lista')foritemindiv_list:url_list.append({'name':item.string,'url':'https://www.tingchina.com/yousheng/{}'.format(item['href'])})returnname,url_list音频地址打开单个章节的链接,在Elements面板中使用章节名作为搜索词,在底部找到一个脚本,其中一部分是音源的地址。在Network面板可以看到音源的url域名和章节列表的域名不一样。获取下载链接时需要注意这一点。defget_mp3_path(url):response=requests.get(url,headers=headers)response.encoding='gbk'soup=BeautifulSoup(response.text,'lxml')script_text=soup.select('script')[-1].stringfileUrl_search=re.search('fileUrl="(.*?)";',script_text,re.S)iffileUrl_search:return'https://t3344.tingchina.com'+fileUrl_search.group(1)下载惊喜总凭空冒出来,把这个https://t3344.tingchina.com/xxxx.mp3放到浏览器里运行,结果是404,肯定是少了一个关键参数。回到上面的Network,仔细观察mp3url,发现url后面有一个key关键字。如下图,这个key是https://img.tingchina.com/play/h5_jsonp.asp?0.5078556568562795的返回值,可以用正则表达式提取key。defget_key(url):url='https://img.tingchina.com/play/h5_jsonp.asp?{}'.format(str(random.random()))headers['referer']=urlresponse=requests.get(url,headers=headers)matched=re.search('(key=.*?)";',response.text,re.S)ifmatched:temp=matched.group(1)returntemp[len(temp)-42:]最后,在__main__中连接上面的代码。if__name__=="__main__":url=input("请输入浏览器页面地址:")dir,url_list=get_detail_urls()foriteminurl_list:audio_url=get_mp3_path(item['url'])key=get_key(item['url'])audio_url=audio_url+'?key='+keyheaders['referer']=item['url']r=requests.get(audio_url,headers=headers,stream=True)withopen(os.path.join(dir,item['name']),'ab')asf:f.write(r.content)f.flush()综上所述,这个Python爬虫比较简单。一个月30元的流量是不够的。有了这个小程序,你就可以在地铁上无流量地听小说了。
