首页 > 其他分享 >【爬虫】项目篇-在https://www.kanunu8.com/book2抓取电子书

【爬虫】项目篇-在https://www.kanunu8.com/book2抓取电子书

时间:2024-04-05 22:56:53浏览次数:23  
标签:www name url book2 content chap book https txt

目录

1)使用正则表达式

#使用requests库和正则表达式抓取在https://www.kanunu8.com/book3/任选的一本电子书
import requests
import re
import os
import time

header = {
    'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}


def main(base_url,book_name):
    os.makedirs(book_name,exist_ok=True)
    #请求网页
    req=requests.get(base_url,headers=header)
    content=req.content.decode(req.apparent_encoding)
    content = re.findall('正文(.*?)</tbody>', content, re.S)
    chap_url_list=get_condition(content)[0]
    chap_name_list=get_condition(content)[1]
    x=0
    for i in range(len(chap_name_list)):
        chap_name=chap_name_list[i]
        chap_url=chap_url_list[i]
        chap_txt=get_txt(base_url,chap_url)
        save(book_name,chap_name,chap_txt)
        if chap_name=='前言':
            print("前言保存成功")
            x=x+1
        else:
            print(f"第{x}章保存成功")
            x=x+1
# 获取 章节标题列表 和 章节url列表
def get_condition(content):
    for item in content:
        chap_url_list=re.findall('[0-9]{6}.html',item)
    for item in content:
        chap_name_list=re.findall('<a href="1831[0-9][0-9].html">(.+)</a></td>',item)
    return chap_url_list,chap_name_list

#获取章节内容
def get_txt(base_url,chap_url):
    base_url=re.search('https://www.kanunu8.com/book3/[0-9]{4}/',base_url).group(0)
    url=base_url+chap_url

    #请求每个章节的url
    req=requests.get(url,headers=header)
    chap_txt=req.content.decode('gbk')
    #选取源码中的书本内容
    #chap_content=re.search("<p>(.+)</p>",chap_content,re.S).group(0)
    chap_txt=re.findall(r'<p>(.*?)</p>',chap_txt,re.S)[0]
    #数据清洗 处理&nbsp、</br>等字符

    chap_txt=chap_txt.replace('&nbsp;',"")
    chap_txt=chap_txt.replace('<br />',"")

    return chap_txt

#保存到当前目录
def save(book_name,chap_name,chap_txt):
    chap_name=chap_name+'.txt'
    with open(os.path.join(book_name,chap_name),'w',encoding='gbk') as file:
       file.write(chap_txt)


if __name__ == '__main__':
    base_url="https://www.kanunu8.com/book3/8259/index.html"
    book_name="孽海花"
    main(base_url,book_name)

2)使用bs4

#使用requests库和beautifulsoup4库在https://www.kanunu8.com/book2上抓取一本电子书

import requests
from lxml import html
from fake_useragent import UserAgent
import cchardet
import os
import re

#获取随机请求头
header={
    'user-agent':UserAgent().random
}
#获取网页源码
def getSource(url):
    req=requests.get(url,headers=header)
    req.encoding=cchardet.detect(req.content)['encoding']
    return req.text.replace("<br />","")

#解析网页
def getUrl(source):
    bs=BeautifulSoup(source,'lxml')

    #获取作者
    actor=bs.select('tr>td[align="center"][height="30"][valign="middle"]')[0].string
    actor=re.search('作者:(.*?) ',str(actor).strip()).group(1)

    #获取书名
    book_name=bs.select('h1>strong>font[color="#dc143c"]')[0].string

    #获取内容简介
    introduction=bs.select('tr[align="left"]>td[class="p10-24"]')[0].strings
    introduction=''.join([i.replace("内容简介:","").strip() for i in introduction])

    print("书名:",book_name,"\n作者:",actor,"\n内容简介:",introduction)
    #获取每个章节链接和章节名
    a=bs.select('tr[bgcolor="#ffffff"]>td>a[href]')
    for i in a:
        chap_name=i.string
        chap_url=i['href']
        chap_txt=getContent(chap_url)
        save(book_name,chap_name,chap_txt)
        print(f'{chap_name}保存成功')

#获取章节链接下的章节内容
def getContent(chap_url):
    url=base_url+chap_url
    print(url)
    source=getSource(url)
    bs=BeautifulSoup(source,'lxml')
    content=str(bs.select('p')[0].string).replace('&nbsp;',"")
    #print(content)
    return content

#保存
def save(book_name,chap_name,chap_txt):
    chap_name=chap_name+'.txt'
    #判断文件夹是否存在
    if not os.path.exists(book_name):
        os.mkdir(book_name)
    with open(os.path.join(book_name,chap_name),'w+',encoding='utf-8') as f:
        f.write(chap_txt)

if __name__ == '__main__':
    base_url = "https://www.kanunu8.com/book3/8196/"
    source=getSource(base_url)
    getUrl(source)

标签:www,name,url,book2,content,chap,book,https,txt
From: https://www.cnblogs.com/Gimm/p/18116338

相关文章

  • 【爬虫】项目篇-豆瓣读书Top250(https://book.douban.com/top250)
    抓取豆瓣读书Top250(https://book.douban.com/top250)每本书的书名、作者、出版社、出版时间、价格、评分等数据,将结果分别保存为csv文件和excel文件importxlwtimportxlsxwriterimportreimportrequestsfromfake_useragentimportUserAgentimportcchardetimporttime......
  • 【爬虫】debug篇-关于fake_useragent无法使用:Error occurred during loading data. Tr
    Erroroccurredduringloadingdata.Tryingtousecacheserverhttps://fake-useragent.herokuapp.com/browsers/0.1.11Traceback(mostrecentcalllast):File"D:\python\lib\site-packages\fake_useragent\utils.py",line154,inloadfori......
  • java中发送https请求报错的问题记录
    问题1thetrustAnchorsparametermustbenon-emptyimportorg.apache.commons.io.IOUtils;importjavax.net.ssl.HttpsURLConnection;importjava.io.IOException;importjava.net.URL;publicclassTestHttps{publicstaticvoidmain(String[]args)throwsI......
  • http免费升级https
    目录背景:http的概念和https的概念简述HTTPS的原理和加密逻辑:https访问的必要性http升级为https后有什么好处:申请免费https证书:背景:首先我们需要了解HTTPS并不是一个全新的协议,而是在HTTP的基础上,通过SSL增加了一层加密协议,从而大大增加了HTTP协议的安全性。......
  • Running the installer as administrator is disabled by default, see https://githu
    在windows安装scoops提示 网上找到解决办法安装失败-安装scoop失败:“默认情况下,以管理员身份运行安装程序处于禁用状态,请参阅https://github.com/ScoopInstaller/Install#for-admin”-堆栈溢出---failedinstallation-Installingscoopfails:"Runningtheinstal......
  • 第6天:基础入门-抓包技术&HTTPS协议&APP&小程序&PC应用&WEB&转发联动
    第六天一、抓包技术-HTTP/S-Web&APP&小程序&PC应用想要抓包都必须要配置代理和端口,这些工具只能抓取HTTP/S协议的数据,走其他协议的数据抓不了有些APP具有代理检测功能,若发现你开启了代理,直接无法访问APP1.Web网页:安装完抓包软件之后,需要在软件上导出CA证书,在浏览器上......
  • 由于JavaScript有两种方式两种写法Creating a regular expression,在线测试网站https:/
    constre=/ab+c/;constre=newRegExp("ab+c");如果要使用第二种方式需要改变flavor和delimiters  RegExp比//需要额外的一次转义可以点击CodeGenerator查看   delimiters的不同会影响所需要的转义......
  • 如何自动申请免费的HTTPS证书?
    在购买域名的时候我相信很多人都遇到了对于证书的问题,之前我也是使用阿里云的免费一年的证书,那时候感觉还好,一年更换一次,但是近期阿里云对于证书的过期时间直接砍到了三个月!让我难以接受,所以我在想吧他直接集成到我的FastGateway中,让他自动申请,自动续期!下面我将教大家如何使用Fast......
  • 免费https证书申请
    一、https是什么“https(全称:HyperTextTransferProtocoloverSecureSocketLayer,超文本传输安全协议),是以安全为目标的HTTP通道,是HTTP的扩展(升级版),用于计算机网络的安全通信”——维基百科简单理解为:在http的基础上,增加安全套接字层(SSL),既可以变成https,作用就是让网站数据传输......
  • python使用request发送x-www-form-urlencoded类型的数据
    场景:当接口的Content-Type类型是x-www-form-urlencoded,使用json类型去请求,无法请求成功解决方法:使用parse.urlencode()方法对json数据进行解码处理,再传入。实例代码如下:importrequestsfromurllibimportparsesession=requests.session()headers={"Content-Type":"app......