NENE 发表于 2022-8-13 06:02

python爬某网站小说全部章节

下载地址:https://yunting.lanzoul.com/ixh8W09gh8lc

#爬取小说项目 2022年8月11日 21点46分 BY:LX
# 查看页面源代码进行分析,提取内容
# 创建协程,进行异布获取
# 下载保存文件
import asyncio
import aiohttp
import aiofiles
import time,os
import requests
from lxml import etree
def list_all_url(url):# 获取当前页面全部文章的子链接
    while 10:
      try:
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.49"
            }
            html = requests.get(url, headers=headers).text
            tree = etree.HTML(html)
            index_href = tree.xpath("//div[@class='zjbox']//dd/a/@href")# 小说的链接
            return index_href
      except:
            print("下载出错了,正在重新尝试...", url)
            time.sleep(3)

async def down_one(url):#下载
    while 10:
      try:
            async with aiohttp.ClientSession() as session:
                async with session.get(url,headres = headers) as resp:
                  article_html = await resp.text()
                  tree = etree.HTML(article_html)
                  book_name = tree.xpath("//*[@id='main']/div/span/a/@title")#小说书名
                  book_title = tree.xpath("//*[@id='main']/h1/text()").strip()#小说文章名
                  book_content = "\n".join(tree.xpath("//*[@id='content']/text()")).replace("全本小说网 www.qb5.tw,最快更新","").replace("最新章节!\n","")#文章内容
                  filename = f'{book_name}\\'# 每个单独按小说名字存放文件夹
                  if not os.path.exists(filename):# 判断存不存在文件夹
                        os.mkdir(filename)# 不存在使用mkdir创建文件夹
                  os.startfile(filename)#打开下载目标的文件夹
                  async with aiofiles.open(f"{filename}{book_title}.txt", mode="w",encoding="utf-8")as f:#写入文件
                        await f.write(book_content)
                  break
      except:
            print("下载出错,正在重新请求下载......"+url)
            time.sleep(.2)
    print(book_title,"..........下载完成!")
async def download(index_href):#构造协程函数
    tasks= []
    for href in index_href:
          list_url = f"{kw}"+href # 拼接小说子链接
          t = asyncio.create_task(down_one(list_url))
          tasks.append(t)
    await asyncio.wait(tasks)

def mian():
    url = f"{kw}"# 小说网址
    index_href = list_all_url(url)# 传值url
    asyncio.run(download(index_href))# 运行协程任务

if __name__ == '__main__':
    while 3:
      try:
            kw = input("例如:“ https://www.qb5.tw/book_22016/ ”\n请粘贴此网站要下载的小说网站网址【‘/’斜杠结尾,不然会出错!】【BY:lx】:")
            if not kw =="":
                mian()
            break
      except:
            print("请粘贴网址下载!")

三三得酒 发表于 2022-8-13 06:03

先收藏了,万一用到呢

mxkslo 发表于 2022-8-13 07:34

6666

今心 发表于 2022-8-13 08:46

正需要,支持楼主,在大牛我只看好你!

popc0527 发表于 2022-8-13 08:46

6666666666

y753900356 发表于 2022-8-13 09:10

谢谢分享!

a602338752 发表于 2022-8-13 09:16

谢谢大牛

Damon0101 发表于 2022-8-13 10:32

谢谢分享

yico1984 发表于 2022-8-13 14:28

谢谢@Thanks!

GFS 发表于 2022-8-15 09:23

感谢楼主分享
页: [1] 2
查看完整版本: python爬某网站小说全部章节