【Python xpath爬虫实战】抓取纵横小说图书信息,并存储到MySQL数据库

写在前面
本篇博客只是为练习xpath的用法,其中的实践案例用其他的更简单方法也可以实现。

想着实战演练一遍(主要是里面的案例无法使用,哭唧唧),找了一下经常爬取的网站,例如淘宝,知网什么的,但是这些网站都需要登录,难度偏大一点,就给否决掉了,最后选到了纵横小说排行榜这个网站,因为这个网站没有什么反爬,不需要登录而且比较符合初始页加详情页这样常用的抓取数据的方法。

下附地址:

小说_小说推荐_好看的完本免费小说推荐- 纵横中文网纵横中文网小说书库,提供最新小说在线阅读,最新小说TXT下载,经典完本小说,包括奇幻小说,玄幻小说,言情小说,都市小说等各类小说尽在纵横中文网小说书库。icon-default.png?t=O83Ahttps://book.zongheng.com/store/c0/c0/b0/u4/p1/v0/s9/t0/u0/i1/ALL.html

网站分析
初始列表页的url

翻页观察


多翻几个页面之后,发现初始页面的url规律十分明显https://book.zongheng.com/store/c0/c0/b0/u4/p{page}

废话不多说,直接上完整代码

import requests
from lxml import etree
import pymysql
import time

db_config = {
    'host': '127.0.0.1',  # 数据库地址
    'user': 'root',  # 数据库用户名
    'password': '123456',  # 数据库密码
    'database': 'cai',  # 数据库名
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}
# 连接数据库
connection = pymysql.connect(**db_config)

for page in range(1, 128):
    time.sleep(1)
    print(f"当前正在请求第{page}页...")
    url = f'https://book.zongheng.com/store/c0/c0/b0/u4/p{page}/v0/s9/t0/u0/i1/ALL.html'

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
    }

    response = requests.get(url=url, headers=headers)
    content = response.content.decode()

    tree = etree.HTML(content)

    bookname = tree.xpath('//div[@class="bookname"]/a/text()')
    src_list = tree.xpath('//div[@class="bookname"]/a/@href')
    img_list = tree.xpath('//div[@class="bookimg"]/a/img/@src')
    author_list = tree.xpath('//div[@class="bookinfo"]/div[2]/a[1]/text()')
    fenlei_list = tree.xpath('//div[@class="bookinfo"]/div[2]/a[2]/text()')
    lianzai_list = tree.xpath('//div[@class="bookinfo"]/div[2]/span[1]/text()')
    choucang_list = tree.xpath('//div[@class="bookinfo"]/div[2]/span[2]/text()')
    new_list = tree.xpath('//div[@class="bookinfo"]/div[4]/a/text()')
    with connection.cursor() as cursor:
        for i in range(len(bookname)):
            # 插入数据
            sql = "INSERT INTO book (bookname, src, img, author, fenlei, lianzai, choucang, new) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
            cursor.execute(sql, (
            bookname[i], src_list[i], img_list[i], author_list[i], fenlei_list[i], lianzai_list[i].strip(),
            choucang_list[i].strip(), new_list[i]))

            # 提交事务
        connection.commit()

# 关闭数据库连接
connection.close()

运行结果:

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值