Python批量爬取小说

利用BeautifulSoup批量爬取笔趣阁小说。

from bs4 import BeautifulSoup
import urllib.request
import re
import os
import threading
import time
# 通过爬虫爬取一本小说

base_url = 'http://www.qu.la' # 笔趣阁首页网址

class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self, threadID, counter,start_page):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.counter = counter
        self.start_page=start_page
        self.bookname, self.url, self.first_url = get_book_by_id(self.counter,self.start_page)
    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        get_chapter_content(self.bookname, self.url, self.first_url)

def get_book_by_id(counter, start_page):
    url = base_url + '/book/' + str(counter + start_page) + '/'
    html_res = urllib.request.urlopen(url)
    soup = BeautifulSoup(html_res, 'html.parser')
    info = soup.select('#wrapper .box_con #maininfo #info')[0]
    bookname = info.contents[1].string
    writer = info.find('p').string
    latest = info.find_all('p')[2].string # 最后更新
    newest = info.find_all('p')[3] # 最新章节
    intro = soup.select('#wrapper .box_con #maininfo #intro')[0].text
    introduction = u"{0}\n{1}\n{2}\n{3}\n{4}\n".format(bookname, writer, latest, newest, intro, intro)
    fw = open("{}.txt.download".format(bookname), 'w', encoding='utf-8')
    fw.write(introduction)
    # 找到第一章的href开始下载
    contents = soup.select('#wrapper .box_con #list dl dt')
    #first_url.find_all('dt')
    for content in contents:
        if str(content).__contains__('一') or str(content).__contains__('正文'):
            start = content
    first_href = start.findNextSibling('dd').contents[1]['href']
    first_url = base_url + first_href
    return bookname, url, first_url


def get_chapter_content(bookname, url, chapter_url):
    fa = open("{0}.txt.download".format(bookname), 'a', encoding='utf-8')
    while(True):
        try:
            html_ret = urllib.request.urlopen(chapter_url, timeout=15).read()
        except:
            continue
        soup = BeautifulSoup(html_ret, 'html.parser')
        chapter = soup.select('#wrapper .content_read .box_con .bookname')[0]
        chapter_url = chapter.findAll('a')[2]['href']
        chapter_name = chapter.h1.string
        chapter_content = soup.select('#wrapper .content_read .box_con #content')[0].text
        chapter_content = re.sub('\s+', '\r\n\t', chapter_content).strip('\r\n')
        fa.write(chapter_name)
        fa.write(chapter_content)
        if chapter_url == "./":
            break
        chapter_url = url + chapter_url
    os.rename('{}.txt.download'.format(bookname), '{}.txt'.format(bookname))
    print("{}.txt下载完成".format(bookname))


#批量获取txt  900-1000
def get_txts(start_page):
    threads = []
    print("当前起始页面:" + str(start_page))
    print("===============创建下载任务====================")
    for i in range(start_page, start_page+10):
        thread_one = myThread(i, i, start_page)
        thread_one.start()
        threads.append(thread_one)
    print("================下载任务创建完成================")
    print("================等待下载任务完成================")
    task_num = len(threads)
    count = 0
    while (1):
        os.system('clear')
        print('============{0:0>8}-{1:0>8} '.format(start_page, start_page + 10) + "下载中===========")
        run_task = 0
        for thread in threads:
            if (thread.isAlive()):
                run_task += 1
                print('{}下载中'.format(thread.bookname))
            else:
                print('{}下载完成'.format(thread.bookname))
        print('\b'+"总任务数:" + str(task_num) + "  已完成任务数:" + str(task_num - run_task)+"\r")
        if (run_task == 0):
            break
        time.sleep(1)
        if (count > 100000):
            count = 0
        else:
            count += 1
    os.system('clear')
    print("所有下载任务已完成")
    time.sleep(2)

if __name__ == "__main__":
    get_txts(20)

运行结果图:
在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Python的pandas和openpyxl库来实现批量爬取Excel内的数据。具体步骤如下: 1. 使用pandas库读取Excel文件,例如: ```python import pandas as pd data = pd.read_excel('filename.xlsx', sheet_name='Sheet1') ``` 其中,`filename.xlsx`为要读取的Excel文件名,`Sheet1`为要读取的工作表名。 2. 遍历读取到的数据,使用爬虫库(比如requests、beautifulsoup等)来爬取相应数据。例如: ```python import requests from bs4 import BeautifulSoup for index, row in data.iterrows(): url = row['url'] # 假设Excel文件中有一个名为'url'的列,存储了需要爬取数据的网址 response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 使用BeautifulSoup解析网页,提取需要的数据 # ... ``` 3. 将爬取到的数据写入Excel文件中。可以使用openpyxl库来实现。例如: ```python from openpyxl import Workbook wb = Workbook() ws = wb.active for index, row in data.iterrows(): # 爬取数据 # ... # 将爬取到的数据写入Excel文件 ws.cell(row=index+1, column=1, value=data1) ws.cell(row=index+1, column=2, value=data2) # ... wb.save('filename.xlsx') ``` 其中,`data1`、`data2`等为爬取到的数据。`ws.cell(row=index+1, column=1, value=data1)`表示将`data1`写入第`index+1`行第1列的单元格中。最后通过`wb.save('filename.xlsx')`保存写入的数据到Excel文件中。 以上是一个基本的批量爬取Excel内数据的流程,具体实现还需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值