Qihuan 发表于 2023-10-14 08:27

17k小说网爬取书架中的小说


import requests
from lxml import etree
import os
headers= {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",
      }
session = requests.session()

def login():
    session.post("https://passport.17k.com/ck/user/login",data={
                            "loginName": "账号",
                            "password": "密码"
                  },headers=headers)


def get_shelf_books():
    '''

    :return:
    '''
    res = session.get("https://user.17k.com/ck/author2/shelf?page=1&appKey=2406394919")
    res.encoding="utf8"
    data = res.json().get("data")
    return data


def get_books(data):

    for bookDict in data:
      # print(bookDict)
      bookID = bookDict.get("bookId")
      bookName = bookDict.get("bookName")
      book_path = os.path.join(root_path,bookName)
      if not os.path.exists(book_path):
            os.mkdir(book_path)
      get_chapter(bookID,book_path,bookName)
def get_chapter(bookID,book_path,bookName):
    res = requests.get(f"https://www.17k.com/list/{bookID}.html")
    # print("res",res)
    res.encoding = "utf8"

    selector = etree.HTML(res.text)
    items = selector.xpath('//dl[@class="Volume"]/dd/a')
    # print(items)


    for item in items:
      chapter_href = item.xpath('./@href')
      chapter_title = item.xpath('./span/text()').strip()
      print("chapter_href", chapter_href)
      print("chapter_text", chapter_title)

      res = requests.get("https://www.17k.com" + chapter_href)
      res.encoding = "utf8"
      chapter_html = res.text
      print(chapter_html)
      selector = etree.HTML(res.text)
      chapter_text = selector.xpath('//div/div[@class="p"]/p/text()')
      # ret = selector.xpath('//div/div[@class="p"]/p/text()')
      print(chapter_text)
      download(book_path, chapter_title,chapter_text)

      print(f'{bookName}书籍的{chapter_title}章节已经下载完成')

def download(book_path, chapter_title,chapter_text):
    chapter_path = os.path.join(book_path, chapter_title)
    with open(chapter_path, "w", encoding="utf8") as f:
      for line in chapter_text:
            f.write(line + "\n")

login()
data = get_shelf_books()
root_path = "我的书架"
ifnot os.path.exists(root_path):
    os.mkdir(root_path)

get_books(data)

酉茸 发表于 2023-10-14 15:46

太生气了,无法HOLD啦 >_<......

3454ki0d0y 发表于 2023-10-14 17:30

66666666666666

vncpuxerwf 发表于 2023-10-14 18:06

强烈支持楼主ing……

谭4142 发表于 2023-10-14 18:23

感恩无私的分享与奉献 :)

tppccjjwlq 发表于 2023-10-14 19:51

楼主加油,我们都看好你哦。

有芝 发表于 2023-10-14 20:00

66666666666666

xdtm8tdy7l 发表于 2023-10-15 02:51

激动人心,无法言表!

ho9j3i9487 发表于 2023-10-15 04:28

感恩无私的分享与奉献 :)

evrcxbnzsu 发表于 2023-10-15 06:51

楼主我爱你!
页: [1] 2 3 4 5 6 7 8 9 10
查看完整版本: 17k小说网爬取书架中的小说