【python学习】当当网分类

本文介绍了一个Python脚本,使用requests和lxml库从当当网上抓取书籍名称、上架时间、出版社和价格数据,并将其存储在CSV文件中。通过分页爬取并实现随机等待时间以避免被封IP。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

 
import requests
from lxml import etree
import csv
import time
import random
import os
os.makedirs('dangdang', exist_ok=True)
writer =csv.writer(open('dangdang/dangdang.csv', 'w', newline='', encoding='utf-8-sig'))
writer.writerow(['图书名称', '上架时间', '出版社', '价格'])

allUrl = ['https://category.dangdang.com/pg{}-cp01.54.92.02.00.00.html'.format(str(i)) for i in range(1, 10)]

count=0

for url in allUrl:
    count = count + 1
    print(url)
    response = requests.get(url)
    response.encoding = 'GB2312'
    html = etree.HTML(response.text)
    print(html)
    allli = html.xpath('//*[@id="component_59"]/li')
    print(allli)
    print('第{}页开始采集'.format(count))
    for li in allli:
        print(li)
        book_name = li.xpath('./a/@title')[0]
        book_time = li.xpath('./p[5]/span[2]/text()')
        book_pub = li.xpath('./p[5]/span[3]/a/text()')  
        book_price = li.xpath('./p[3]/span[1]/text()')
        
        if book_time:
            book_time = book_time[0].replace('/','')
        else:
            book_time = '无'
            
        if book_pub:
            book_pub = book_pub[0] 
        else:
            book_pub = '暂无'
            
        if book_price:
            book_price = book_price[0].strip('¥')
        else:
            book_price = 0
        
        
        rowInfo = (
                   book_name,   
                   book_time,  
                   book_pub,  
                   book_price
                    )
        print(rowInfo)
        writer.writerow(rowInfo)
    print('第{}页采集完成!'.format(count)) 
    time.sleep(random.randint(3, 10))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值