爬取小说(步骤五)python

作者: 肥宅_Sean | 来源:发表于2018-01-14 12:51 被阅读267次

    假设各位老哥已经安装好了bs4 requests这些库了
    这个小说是随便挑的,各位也就不用太介意(仅供各位学习)
    python3 实现,网上用python2做爬虫的太多了,但用python3的还是比较少

    • 通过步骤四中 寻找到的那些url来对逐步访问,获取txt并写入(这个在之前也都讲过了)

    • 没有看过 步骤一 的朋友们可以点击下面的链接看看步骤一先
      点击查看步骤一

    • 没有看过 步骤二 的朋友们可以点击下面的链接看看步骤二先
      点击查看步骤二

    • 没有看过 步骤三 的朋友们可以点击下面的链接看看步骤三先
      点击查看步骤三

    • 没有看过 步骤四 的朋友们可以点击下面的链接看看步骤四先
      点击查看步骤四

    • 本来代码是会很简单的,但为了不被禁什么的。就加了模拟人的休息(sleep)

    • 代码会自动下载到E:/txt/这个文件夹中(没有的话,会自动添加这个文件夹)

    • 会自动寻找到这个小说的名字(并存储下来,以这个名字作为文件名)

    • 通过步骤四的筛选使得这些链接都是包括有小说内容的(一般会有作者发一些公告的章节,对于这个进行了一定的筛选)

    下载过程的效果
    import requests
    from bs4 import BeautifulSoup
    import os
    import time
    import random
    urls = []
    title = []
    content_url = "http://www.biquge.com.tw/4_4038"
    kv = {'user_agent': 'Mozilla/5.0'}  # 表示是一个浏览器
    root = 'E:/txt/'     # 设置根目录,将会把txt文件放到这个文件夹中的
    book_name = '1.txt'  # 设置一个Default书名(虽然在后来肯定是会找到一个名字的)
    count = 0
    try:
        r = requests.get(content_url, headers=kv)  # 表示自己是一个浏览器
        r.raise_for_status()   # 如果有问题就会raise一个问题
        r.encoding = r.apparent_encoding  # 根据网页返回的编码 进行调整
        soup = BeautifulSoup(r.text, 'html.parser')
        content_list = soup.find(id='list')
        chapter_list = soup.find_all('dd')
        meta = soup.find('head').find(attrs={'property': "og:novel:book_name"})
        book_name = meta['content'] + '.txt'
        print(book_name[:book_name.index('.txt')] + '写入中')
        for chapter in chapter_list:  # 整合得到所有跟内容有关的链接(会有哪些跟内容无关的章节的)
            if '第' in chapter.find('a').text and '章' in chapter.find('a').text:
                title.append(chapter.find('a').text)
                urls.append(content_url[:content_url.rindex('/')] + chapter.find('a')['href'])
        first = True
        for i, url in enumerate(urls):
            r = requests.get(url, headers=kv)
            r.raise_for_status()
            r.encoding = r.apparent_encoding
            soup = BeautifulSoup(r.text, 'html.parser')
            content = soup.find(id='content')
            string = content.text.replace('\u3000', '').replace('『', '“').replace('』', '”').replace('\ufffd', '').replace('\u30fb', '')  # 去除不相关字符
            string = string.split('\xa0')  # 编码问题解决
            string = list(filter(lambda x: x, string))
            for ii in range(len(string)):
                string[ii] = '    ' + string[ii]
                if "本站重要通知" in string[ii]:  # 去除文末尾注
                    t = string[ii].index('本站重要通知')
                    string[ii] = string[ii][:t]
            string = '\n'.join(string)
            string = '\n' + title[i] + '\n' + string + '\n'
            string = string.replace('\ufffd', '').replace('\u30fb', '').replace('\u3000', '')
            if not os.path.exists(root):
                os.mkdir(root)  # 如果没有这个文件夹,就会创建一个
            if first:  # 如果是第一次写入的话,会将原来的内容清空,然后再写入
                first = False
                with open(root + book_name, 'w') as f:
                    f.write(string)
                    f.close()
            else:  # 反之,则直接在文章末尾处添加
                with open(root + book_name, 'a') as f:
                    f.write(string)
                    f.close()
            print(title[i].replace('\ufffd', ''), '写入成功')  # 这是因为我担心这个字符是在title中的
            ti = random.randint(0, 2)
            if ti == 0:
                count += 1
            else:
                count = 0
            if count < 3:
                time.sleep(ti)
            else:
                time.sleep(30)
    except:
        pass
    

    爬取小说(步骤六)python

    相关文章

      网友评论

      • 肥宅_Sean:又用其他小说的目录链接跑了一遍哈哈哈做了点小修改速度上快了点了hhh

      本文标题:爬取小说(步骤五)python

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