首页 > 编程语言 >python爬虫实战-小说爬取

python爬虫实战-小说爬取

时间:2023-11-13 14:15:21浏览次数:39  
标签:novel classification python self 爬虫 爬取 table div data

python爬虫实战-小说爬取

基于requests模块与lxml模块编写的爬虫,目标小说网站为 https://www.hongxiu.com/category/

基本思路

  • 主要内容分为三个部分
    1. 使用requests模块获取网页内容
    2. 使用lxml模块进行网页解析
    3. 将解析出来的数据存储进MySQL数据库中
  1. 获取网页内容

    • 网站分析

      获取各个分类的href标签

      红袖小说爬虫

    • 代码如下

          def novel_sort_link(self):
              novel_website = requests.get(self.url).text
              # print(novel_website)
              novel_classification_link = etree.HTML(novel_website)
              novel_classification = novel_classification_link.xpath(
                  '/html/body/div[1]/div[2]/div[2]/div/div/div[1]/div/ul/li/a')
              classification_href_list = list()
              for classification in set(novel_classification):
                  href = self.url + classification.xpath('./@href')[0].replace('/category/', '')
                  classification_href_list.append(href)
              return classification_href_list
      
  2. 解析数据

    • 获取书名、作者、状态、热度、简介等数据

      红袖小说爬虫2

    • 代码如下:

          def analysis(self, classification_url_link):
              for classification_url in classification_url_link:
                  # print(classification_url)
                  for num in range(1, 51):
                      url = classification_url.replace(classification_url[-1], str(num))
                      novel_response_text = requests.get(url).text
                      # print(novel_response_text)
                      novel_response_html = etree.HTML(novel_response_text)
                      novel_response = novel_response_html.xpath('/html/body/div[1]/div[2]/div[3]/div[2]/div[1]/ul/li')
                      for novel in novel_response:
                          novel_dict = dict()
                          novel_dict['novel_name'] = novel.xpath('./div[2]/h3/a/@title')[0]
                          novel_dict['author'] = novel.xpath('./div[2]/h4/a/text()')[0]
                          novel_dict['classify'] = novel.xpath('./div[2]/p[1]/span[1]/text()')[0]
                          novel_dict['state'] = novel.xpath('./div[2]/p[1]/span[2]/text()')[0]
                          novel_dict['number'] = novel.xpath('./div[2]/p[1]/span[3]/text()')[0]
                          novel_dict['synopsis'] = novel.xpath('./div[2]/p[2]/text()')[0].replace('\r\n', '').replace(' ', '')
                          # print(novel_dict)
                          
      
  3. 将数据存储进数据库中

    • 调用将数据存储进mysql数据库的类

      MySQL().main(table_name='hongxiu_novel', data=novel_dict)
      
    • 连接数据库

       def connect_to_database(self):
              """连接到MySQL数据库"""
              self.connection = pymysql.connect(
                  host='localhost',
                  user='root',
                  password='password',
                  database='reptile_text',
                  port=3306
              )
      
          def disconnect_from_database(self):
              """断开与MySQL数据库的连接"""
              if self.connection:
                  self.connection.close()
      
    • 判断数据表是否存在

          def table_exists(self, table_name):
              """检查数据表是否存在"""
              self.connect_to_database()
              cursor = self.connection.cursor()
              cursor.execute("SHOW TABLES LIKE '{}'".format(table_name))
              result = cursor.fetchone()
              cursor.close()
              self.disconnect_from_database()
              if result:
                  return True
              else:
                  return False
      
    • 数据表不存在则根据提供的数据字典键来进行创建新数据表

          def create_table(self, table_name, data):
              """创建包含文本列的数据表"""
              self.connect_to_database()
              cursor = self.connection.cursor()
      
              columns = []
              for key, value in data.items():
                  column_type = 'TEXT'
                  columns.append(f'{key} {column_type}')
      
              create_table_sql = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(set(columns))})"
              cursor.execute(create_table_sql)
              print('数据表创建成功')
      
              cursor.close()
              self.disconnect_from_database()
      
    • 将数据插入进数据库中

          def insert_data(self, table_name, data):
              """在表中插入数据"""
              self.connect_to_database()
              cursor = self.connection.cursor()
              keys = ', '.join(data.keys())
              values = ', '.join([f"'{value}'" for value in data.values()])
              one_key = list(data.keys())[0]
              select_sql = f"SELECT * FROM {table_name} WHERE {one_key} ='{data[one_key]}'"
              cursor.execute(select_sql)
              result = cursor.fetchone()
      
              if result:
                  print(f"数据已存在: {data}")
              else:
                  insert_sql = f"INSERT INTO {table_name} ({keys}) VALUES ({values})"
                  cursor.execute(insert_sql)
                  print(f"插入数据: {data}")
      

完整代码

  1. hongxiu_novel.py完整代码

    # coding:utf-8
    import requests
    from lxml import etree
    from reptile_text.mysql_data import MySQL
    
    
    class HongXiu(object):
        def __init__(self):
            self.url = 'https://www.hongxiu.com/category/'
    
        def novel_sort_link(self):
            novel_website = requests.get(self.url).text
            # print(novel_website)
            novel_classification_link = etree.HTML(novel_website)
            novel_classification = novel_classification_link.xpath(
                '/html/body/div[1]/div[2]/div[2]/div/div/div[1]/div/ul/li/a')
            classification_href_list = list()
            for classification in set(novel_classification):
                href = self.url + classification.xpath('./@href')[0].replace('/category/', '')
                classification_href_list.append(href)
            return classification_href_list
    
        def analysis(self, classification_url_link):
            for classification_url in classification_url_link:
                # print(classification_url)
                for num in range(1, 51):
                    url = classification_url.replace(classification_url[-1], str(num))
                    novel_response_text = requests.get(url).text
                    # print(novel_response_text)
                    novel_response_html = etree.HTML(novel_response_text)
                    novel_response = novel_response_html.xpath('/html/body/div[1]/div[2]/div[3]/div[2]/div[1]/ul/li')
                    for novel in novel_response:
                        novel_dict = dict()
                        novel_dict['novel_name'] = novel.xpath('./div[2]/h3/a/@title')[0]
                        novel_dict['author'] = novel.xpath('./div[2]/h4/a/text()')[0]
                        novel_dict['classify'] = novel.xpath('./div[2]/p[1]/span[1]/text()')[0]
                        novel_dict['state'] = novel.xpath('./div[2]/p[1]/span[2]/text()')[0]
                        novel_dict['number'] = novel.xpath('./div[2]/p[1]/span[3]/text()')[0]
                        novel_dict['synopsis'] = novel.xpath('./div[2]/p[2]/text()')[0].replace('\r\n', '').replace(' ', '')
                        # print(novel_dict)
                        MySQL().main(table_name='hongxiu_novel', data=novel_dict)
    
        def main(self):
            classification_url_link = self.novel_sort_link()
            self.analysis(classification_url_link)
    
    
    if __name__ == '__main__':
        HongXiu().main()
    
  2. mysql_data.py完整代码

    # -*- coding:utf-8 -*-
    import pymysql
    
    
    class MySQL(object):
        def __init__(self):
            self.connection = None
    
        def connect_to_database(self):
            """连接到MySQL数据库"""
            self.connection = pymysql.connect(
                host='localhost',
                user='root',
                password='password',
                database='reptile_text',
                port=3306
            )
    
        def disconnect_from_database(self):
            """断开与MySQL数据库的连接"""
            if self.connection:
                self.connection.close()
    
        def create_table(self, table_name, data):
            """创建包含文本列的数据表"""
            self.connect_to_database()
            cursor = self.connection.cursor()
    
            columns = []
            for key, value in data.items():
                column_type = 'TEXT'
                columns.append(f'{key} {column_type}')
    
            create_table_sql = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(set(columns))})"
            cursor.execute(create_table_sql)
            print('数据表创建成功')
    
            cursor.close()
            self.disconnect_from_database()
    
        def table_exists(self, table_name):
            """检查数据表是否存在"""
            self.connect_to_database()
            cursor = self.connection.cursor()
            cursor.execute("SHOW TABLES LIKE '{}'".format(table_name))
            result = cursor.fetchone()
            cursor.close()
            self.disconnect_from_database()
            if result:
                return True
            else:
                return False
    
        def insert_data(self, table_name, data):
            """在表中插入数据"""
            self.connect_to_database()
            cursor = self.connection.cursor()
            keys = ', '.join(data.keys())
            values = ', '.join([f"'{value}'" for value in data.values()])
            one_key = list(data.keys())[0]
            select_sql = f"SELECT * FROM {table_name} WHERE {one_key} ='{data[one_key]}'"
            cursor.execute(select_sql)
            result = cursor.fetchone()
    
            if result:
                print(f"数据已存在: {data}")
            else:
                insert_sql = f"INSERT INTO {table_name} ({keys}) VALUES ({values})"
                cursor.execute(insert_sql)
                print(f"插入数据: {data}")
    
            self.connection.commit()
            cursor.close()
            self.disconnect_from_database()
    
        def main(self, table_name, data):
            if self.table_exists(table_name):
                print('数据表已存在')
                self.insert_data(table_name, data)
            else:
                print('数据表不存在')
                self.create_table(table_name, data)
                self.insert_data(table_name, data)
    

标签:novel,classification,python,self,爬虫,爬取,table,div,data
From: https://www.cnblogs.com/moyiwang/p/17828959.html

相关文章

  • python 脚本打包成exe可运行文件
    在Python 3中使用Tkinter编写GUI应用程序既简单又有趣。然而,如果你想与其他人分享你的应用程序,那么你需要将源代码和必要的库文件一起打包成一个可执行文件。本文将介绍如何使用pyinstaller将Python 3脚本打包成一个.exe文件并将Tkinter应用程序部署到其他计算机上。安装pyinstal......
  • 基于Python+Django的酒店管理系统网站开发
    一、介绍酒店管理系统。基于Python开发,前端使用HTML、CSS、BootStrap等技术搭建页面,后端使用Django框架处理用户响应请求,主要功能如下:分为普通用户和管理员两个角色普通用户:登录、注册、查看房间详情、收藏、购买、发布评论、对房间进行评分、查看个人订单、个人信息编辑、充......
  • Python的GUI图形界面工具大全
     来源:http://www.shanhubei.com/archives/2833.html总结了一下Python下的图形界面GUI工具,暂时能找到的资料就这么多,后续会补充推荐学习资料。图形界面的定义图形界面图形用户界面(GraphicalUserInterface,简称GUI,又称图形用户接口)是指采用图形方式显示的计算机操作用户界......
  • Rust写的爬虫代码抓取精美的图片
    Rust是一种系统级编程语言,它的设计目标是安全、并发和高效。Rust的爬虫库非常丰富,例如scraper、select、reqwest等等。这些库提供了许多功能,例如HTML解析、HTTP请求、异步处理等等,使得Rust成为一个非常适合编写爬虫的语言。以下是一个使用reqwest和scraper库编写的简单爬虫示例,用于......
  • 爬虫-python面对对象-工具
    一、面向对象基础1、面向对象思想简介软件编程就是将我们的思维转变成计算机能够识别语言的一个过程什么是面向过程?自上而下顺序执行,逐步求精其程序结构是按功能划分为若干个基本模块,这些模块形成一个树状结构;各模块之间的关系尽可能简单,在功能上相对独立每一模块内部......
  • 利用Biopython – Pairwise Alignment计算序列相似度
    #ImportlibrariesfromBioimportpairwise2fromBio.SeqimportSeq#Creatingsamplesequencesseq1=Seq("TGTGACTA")seq2=Seq("CATGGTCA")#Findingsimilaritiesalignments=pairwise2.align.globalxx(seq1,seq2)#Showingresultsformat......
  • Linux服务器不自动杀死超内存Python程序导致服务器卡死掉线
    状态:Python处理大数据时,内存占用超过服务器可用内存,但是服务器并没有杀死该进程,而是被卡死无法通过ssh进入解决方向:一、设置系统内存限制:使用 ulimit-a查看系统参数ulimit-a 命令的结果中会显示各种资源的限制参数。以下是一些常见参数及其含义:corefilesize (ulimit......
  • pythonDay11
    文件修改的两种方式 函数的定义和调用(无参函数) 有参函数及应用场景(多次调用值:unf,传入不同的参数即可) 空函数及有参函数的应用场景(print()里输入错误,应该是:有参函数应用场景) 调用函数的三种方式  函数返回值的三种方式 ......
  • 图片转Excel的python小工具
    安装软件:pipinstallcvpipinstallpaddlepaddle pipinstallpandas-ihttps://pypi.douban.com/simple pipinstallpaddleocr==2.6.0.2-ihttps://pypi.tuna.tsinghua.edu.cn/simplepipinstallpaddleocr paddleocr-2.7.0.3-py3-none-any.whl 代码: pic2Excel.......
  • python基础
    一、基本语法注释 单行注释# 快捷键command+/ 多行注释"""""" 也可以和变量名结合写多行变量值变量 在python里,变量必须赋值 命名规则: 字母、数字、下划线,不能以数字开头 不要使用python内置关键字 命名规范: 1、见名知意 2、全小写下划线连接检查关键字......