基于Python爬虫对当当网图书信息采集(10w条数据)+代码

  • 柱状图展示不同价格区间的图书数量。
出版社排名图
  • 折线图展示出版社的图书数量排名。
作者出书数量图
  • 条形图展示作者的出书数量。
评论热力图
  • 热力图展示图书评论的分布情况。

结论

通过对10万条当当图书网数据的采集和分析,我们能够深入理解当前图书市场的动态,为出版社、作者和读者提供有价值的市场洞察。


在这里插入图片描述在这里插入图片描述
在这里插入图片描述

完整代码

def get\_page\_tree(url):
    from requests.adapters import HTTPAdapter
    page = requests.session()
    page.mount('http://',HTTPAdapter(max_retries=80))
    page.mount('https://',HTTPAdapter(max_retries=80))
    page = page.request("GET",url=url,timeout=120)
    print('page ' , page ,page.text)

    tree = etree.HTML(page.text)
    return tree


# xpath语法 获取li对象 因为li标签不只一个 所以用lis
def get\_lis(tree):
    lis = tree.xpath('//\*[@id="search\_nature\_rg"]/ul/li')
    return lis


def deal\_save(url , pressN,page_index):
    global sum
    global row
    tree = get\_page\_tree(url)
    # 获取到lis对象
    lis = get\_lis(tree)
    # time.sleep(random.randint(1,3))
    print("正在爬取...", url)
    # 遍历lis 返回index下标和item
    try:
        for c, i in enumerate(lis):
            # 根据xpath规则提取图书标题
            name = i.xpath('a/@title')
            name = str(name[0])
            name = name.strip()
            # 根据xpath规则提取图书描述
            desc = i.xpath('p[2]/text()')
            # 根据xpath规则提取图书价格和该书电子书的价格
            price_normal = i.xpath('p[3]/span[1]/text()')  # 纸质书的价格

            price_normal = price_normal[0]
            price_net = i.xpath('p[3]/a/i/text()')  # 电子书的价格
            # 根据xpath规则提取图书的作者
            author = i.xpath('p[@class="search\_book\_author"]/span[1]/a/text()')  # 作者
            if len(author) == 0:
                author = '没有作者'
            else:
                author = author[0]
            # 根据xpath规则提取图书出版时间
            press_time = i.xpath('p[@class="search\_book\_author"]/span[2]/text()')
            if len(press_time) == 0:
                press_time = '出版时间为空'
            else:
                press_time = press_time[0][2:]
            # 根据xpath规则提取图书出版社
            press = i.xpath('p[@class="search\_book\_author"]/span[3]/a/text()')
            if len(press) == 0:
                press = '出版社为空'
            else:
                press = press[0]
            if len(desc) != 0:
                desc = desc[0]
            else:
                desc = "null"
            if len(price_net) != 0:
                price_net = price_net[0]
            else:
                price_net = "暂无电子书"
            sum += 1
            # 输出信息
            print('第{}页--第{}条数据--累计爬取{}条:'.format(page_index, c, sum))
            print('书名:《{}》'.format(name))
            print('图书价格:{}'.format(price_normal))
            print('电子书价格:{}'.format(price_net))
            print('作者:{}'.format(author))
            print('出版社:{}'.format(press))
            print('出版时间:{}'.format(press_time))
            print('\*' \* 25)
            time.sleep(0.1)
            # 保存信息
            sheet.write(row, 0, name)
            sheet.write(row, 1, desc)
            sheet.write(row, 2 , price_normal)
            sheet.write(row, 3 , price_net)
            sheet.write(row, 4 , author)
            sheet.write(row, 5 , press_time)
            sheet.write(row, 6 , press)
            row = row + 1

    except Exception as e:
        print(e)



# 主要爬虫程序  遍历给定出版社 所有的图书
def start (url , pressN):
    # 获取page的etree
    new_url = url.format(press_name, 1)
    tree = get\_page\_tree(new_url)
    # 获取该出版社展示图书总页数
    total = tree.xpath('//\*[@id="12810"]/div[5]/div[2]/div/ul/li[9]/a/text()')[0]
    print('{}一共{}页'.format(pressN,total))
    # 全局变量的sum 总数
    global sum
    # time.sleep(2)
    # 线程保存的数组
    threads = [ ]
    # 遍历所有页面 从1到total
    for page_index in range(1, int(total) + 1):
        time.sleep(0.2)
        temp_url = url.format(pressN,page_index)
        temp\_t = Thread(target=deal_save , args = ( temp_url,press_name,page_index, ))
        threads.append(temp\_t)
        temp\_t.start()
    for index, t in enumerate(threads):
        t.join()


if __name__ == '\_\_main\_\_':
    # 通过file读取所有出版社 保存为list数组
    s = time.time()
    press = []


    with open('Press.txt' , 'r' , encoding='utf-8') as f :
        a = f.read()
        f.close()
    # 拆封数据
    press = a.split('\n')
    url = 'http://search.dangdang.com/?key={}&page\_index={}'
    # 遍历所有出版社
    for press_name in press:
        start(url , press_name)
        print('正在采集{}'.format(press_name))

    end = time.time()
    book.save('当当网图书汇总.xlsx')
    print(  '共花费:' ,str((end-s) ) , 's ,共计爬取:{}条'.format(sum))

 **自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。**

**深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!**

**因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**

![img](https://img-blog.csdnimg.cn/img_convert/c832257990e34528d758bcbd9d4481a3.png)

![img](https://img-blog.csdnimg.cn/img_convert/4071f1327cd28f9b9d1be2cd0e71cbda.png)

![img](https://img-blog.csdnimg.cn/img_convert/8a8932d2aef3941c7074e35fe00a2794.png)

![img](https://img-blog.csdnimg.cn/img_convert/9975a56b6ba08cddfac3367835b858db.png)

![img](https://img-blog.csdnimg.cn/img_convert/6c361282296f86381401c05e862fe4e9.png)

![img](https://img-blog.csdnimg.cn/img_convert/9f49b566129f47b8a67243c1008edf79.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!**

**由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新**

**如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)**

8edf79.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!**

**由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新**

**如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)**

<img src="https://img-community.csdnimg.cn/images/fd6ebf0d450a4dbea7428752dc7ffd34.jpg" alt="img" style="zoom:50%;" />
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
爬取当当网Python图书信息,可以使用Python编写爬虫程序来实现。首先,通过观察当当网的搜索URL,可以得到搜索关键字"Python"的URL链接为和。其中,是第一页的搜索结果,是第二页的搜索结果。爬虫程序可以通过模拟HTTP请求访问搜索结果页面,然后解析页面内容来获取图书信息。 以下是一个简单的示例代码,演示如何使用Python爬虫获取当当网Python图书信息: ```python import requests from bs4 import BeautifulSoup def get_book_info(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') book_list = soup.find_all('div', class_='name') for book in book_list: title = book.find('a').text.strip() author = book.find('span', class_='t1').text.strip() price = book.find('span', class_='search_now_price').text.strip() print(f"书名: {title}, 作者: {author}, 价格: {price}") # 爬取第一页的图书信息 url1 = "http://search.dangdang.com/?key=Python&act=input" get_book_info(url1) # 爬取第二页的图书信息 url2 = "http://search.dangdang.com/?key=Python&act=input&page_index=2" get_book_info(url2) ``` 这段代码使用了`requests`库发送HTTP请求,使用了`BeautifulSoup`库解析HTML页面。它通过指定的URL链接发送请求,并使用CSS选择器查找图书信息的相关元素。在示例中,我们获取了书名、作者和价格,并打印出来。 可以通过调用`get_book_info`函数来获取当当网Python图书信息。传入不同的URL链接可以获取不同页数的图书信息。你可以根据需要,进一步处理获取到的图书信息,比如存储到数据库或写入文件中。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【爬虫】4.5 实践项目——爬取当当网图书数据](https://blog.csdn.net/qq_57268251/article/details/131177457)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值