爬取17K小说网书架内的小说

import threading

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()
accountNumber = input("请输入你的17K小说网账号:")
password = input("请输入你的登录密码:")
def login():
    session.post("https://passport.17k.com/ck/user/login",data={
                            "loginName": accountNumber,
                            "password": password
                    })


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")

    res.encoding = "utf8"

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



    for item in items:
        chapter_href = item.xpath('./@href')[0]
        chapter_title = item.xpath('./span/text()')[0].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[contains(@class,"content")]/div[@class="p"]/p[position()<last()]/text()')
        # ret = selector.xpath('//div[contains(@class,"content")]/div[@class="p"]/p[position()<last()]/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 = "我的书架"
if  not os.path.exists(root_path):
    os.mkdir(root_path)

get_books(data)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Python编写的起点小说的多线程虫代码: ```python import requests from lxml import etree from queue import Queue import threading # 定义虫类 class Spider(): def __init__(self, url, headers): self.url = url self.headers = headers self.session = requests.Session() self.session.headers.update(headers) # 获小说列表 def get_novel_list(self): response = self.session.get(self.url) html = etree.HTML(response.text) novel_list = html.xpath('//div[@class="book-mid-info"]/h4/a/@href') return novel_list # 获小说信息 def get_novel_info(self, novel_url): response = self.session.get(novel_url) html = etree.HTML(response.text) novel_info = {} novel_info['title'] = html.xpath('//div[@class="book-info "]/div[@class="book-info "]/h1/em/text()')[0] novel_info['author'] = html.xpath('//div[@class="book-info "]/div[@class="book-info "]/h1/span/a/text()')[0] novel_info['intro'] = html.xpath('//div[@class="book-intro"]/p/text()')[0] novel_info['word_count'] = html.xpath('//div[@class="book-info "]/div[@class="book-info "]/p/span[1]/text()')[0] return novel_info # 定义线程类 class SpiderThread(threading.Thread): def __init__(self, spider, novel_queue): threading.Thread.__init__(self) self.spider = spider self.novel_queue = novel_queue def run(self): while True: try: novel_url = self.novel_queue.get(False) novel_info = self.spider.get_novel_info(novel_url) print(novel_info) except: break # 定义主函数 def main(): url = 'https://www.qidian.com/all' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} spider = Spider(url, headers) novel_list = spider.get_novel_list() # 创建小说队列 novel_queue = Queue() # 将小说列表加入队列 for novel_url in novel_list: novel_queue.put(novel_url) # 创建线程 threads = [] for i in range(5): spider_thread = SpiderThread(spider, novel_queue) spider_thread.start() threads.append(spider_thread) # 等待所有线程结束 for t in threads: t.join() if __name__ == '__main__': main() ``` 该代码使用了Python的requests库和lxml库来进行和解析,使用了多线程来提高效率。首先定义了一个Spider类来实现小说列表和小说信息的功能,然后定义了一个SpiderThread类来作为线程,最后在主函数中创建小说队列和线程,并等待所有线程结束。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值