美文网首页
长篇保存优化 Retry爬空重试 Python 野站小说通用爬取

长篇保存优化 Retry爬空重试 Python 野站小说通用爬取

作者: 辣辣不乖 | 来源:发表于2020-12-19 17:21 被阅读0次

代码简要说明

一般小说野站URL格式

  • 域名 + 二级路径(书籍目录)+ 三级路径(章节内容)
  • 域名 + 三级路径(二级页面爬取的相对路径已包含二级路径)

self.url 域名路径根据以上情况写入 例如: http://www.biquge.infohttp://www.biquge.info/1_1245/

self.new_url 二级页面路径(书籍目录)例如:http://www.biquge.info/1_1245/

div=soup.find_all('div',id='list') 章节列表特征 例:div , 'id = list' 或 class_ = lists

texts=soup.find_all(id = 'content') 内容页面特征 例:id = 'content'class_ = mian

以上根据F12浏览器审查填写即可

完整爬取代码

# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import sys
from retrying import retry

class download_txt(object):
    
    def __init__(self):
        self.url='http://www.biquge.info' #注意部分内容页面路径已包含上级路径
        self.new_url = 'http://www.biquge.info/1_1245/'
        self.names = []             #存放章节名
        self.urls = []              #存放每一个章节的链接
        self.nums = 0               #章节数目
    
    def get_url(self):
        
        try:
            headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.XXXX.XXX Safari/537.36'}
            r=requests.get(url=self.new_url,headers=headers,timeout=30)
            r.raise_for_status()
            r.encoding=r.apparent_encoding
            html=r.text
            #print(html)
            soup=BeautifulSoup(html,'html.parser')
            div=soup.find_all('div',id='list')
            print(div)
            a_bf=BeautifulSoup(str(div[0]),'html.parser')
            a=a_bf.find_all('a')
            self.nums=len(a[0:])
            for each in a[0:]:
                self.names.append(each.string)
                self.urls.append(self.url+each.get('href'))
            
        except:
            return "爬取链接失败"

    @retry(stop_max_attempt_number=10, wait_fixed=1000) #构建retry装饰器,重试次数,等待时间毫秒
    def get_contents(self,url):
        r=requests.get(url,timeout=10)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        html=r.text
        soup=BeautifulSoup(html,'html.parser')
        texts=soup.find_all(id='content')
        texts=texts[0].text.replace('\xa0'*8,'\n\n')
        return texts
        
    def save_txt(self,name,path,text):
        
        with open(path,'a',encoding='utf-8') as f:
            f.write(name+'\n')
            f.writelines(text)
            f.write('\n\n')
            
            
if __name__=='__main__':
    d=download_txt()
    d.get_url()
    print('开始下载小说《NEW》')

    for i in range(d.nums):
        d.save_txt(d.names[i],'new.txt',d.get_contents(d.urls[i]))
        sys.stdout.write('已经下载:' + str(i) + '/' + str(d.nums) + '\r')
        #sys.stdout.flush()
    print('《NEW》下载完成')

相关文章

网友评论

      本文标题:长篇保存优化 Retry爬空重试 Python 野站小说通用爬取

      本文链接:https://www.haomeiwen.com/subject/aeyknktx.html