欢迎来到Louis的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

Python 爬取笔趣看小说

# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
import requests
import sys


class DownLoader(object):
    def __init__(self):
        self.server = 'http://www.biqukan.com/'
        self.target = 'http://www.biqukan.com/0_790/'
        self.header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebK'
                                     'it/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}
        self.name = []
        self.urls = []
        self.num = 0

    def get_downloader_url(self):
        req = requests.get(url=self.target, headers=self.header)
        html = req.text
        div_bf = BeautifulSoup(html, 'lxml')
        div = div_bf.find_all('div', class_='listmain')
        a_bf = BeautifulSoup(str(div[0]), 'lxml')
        a = a_bf.find_all('a')
        self.num = len(a[16:])
        for i in a[16:]:
            self.name.append(i.string)
            self.urls.append(self.server+i.get('href'))

    def get_content(self, target):
        req = requests.get(target, headers=self.header)
        html = req.text
        con_bf = BeautifulSoup(html, 'lxml')
        con = con_bf.find_all('div', class_='showtxt')
        con = con[0].text.replace('\xa0'*8, '\n\n')
        return con

    def writer(self, name, path, text):
        write_flag = True
        with open(path, 'a', encoding='utf-8') as f:
            f.write(name+'\n')
            f.writelines(text)
            f.write('\n\n')

if __name__ == '__main__':
    dl = DownLoader()
    dl.get_downloader_url()
    print('《元尊》开始下载:')
    for i in range(dl.num):
        dl.writer(dl.name[i], '元尊.txt', dl.get_content(dl.urls[i]))
        sys.stdout.write("已下载:%.3f" % float(i/dl.num)+'\r')
        sys.stdout.flush()
    print('下载完成')

 

posted on 2018-03-28 12:23  Louiszj  阅读(970)  评论(0编辑  收藏  举报

导航