笔趣看小说全部章节爬取实战

import requests
from bs4 import BeautifulSoup
import os
# 本地写入
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}
def getPage(url):
    re=requests.get(url,headers=headers)
    re.raise_for_status()
    re.encoding=re.apparent_encoding
    soup=BeautifulSoup(re.text,'lxml')
    return soup
if __name__ == '__main__':
    url='https://www.bqkan.com/38_38836/'
    soup=getPage(url)
    book_name=soup.select('.info h2')[0].text
    book_author=soup.select('.small span')[0].text
    last_time=soup.select('.small .last')[0].text
    last_chapter=soup.select('.small .last a')[0].text
    print("书名:",book_name,book_author,last_time,"最新章节:",last_chapter)
    # 以书名创建文件夹
    k=os.path.exists(book_name) # k为bool类型
    if k==False:
        # 没有才创建
        os.makedirs(book_name)
    # 获取所有单章链接
    links=soup.select('.listmain dd a')
    # 前12个为最新章节,其余为正式章节,包含最新章节
    for item in links[12:]:
        href='https://www.bqkan.com'+item['href']
        print(href,item.string)
        soup=getPage(href)
        content=soup.select('.showtxt')[0].text
        content=content.replace('app2();read2();  ','')
        content=content.replace('  ','\n\n')
        print(">>>正在写入文件")
        with open("%s/%s.txt"%(book_name,item.string),'w',encoding='utf-8') as file:
            file.write(content)
    print(">>>全部章节爬取完毕!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员班长

感谢您的一路相伴

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值