Python爬取当网书籍数据并数据可视化展示

yizhihongxing

本文将详细讲解如何使用Python爬虫爬取当网书籍数据并进行数据可视化展示的完整攻略,包括数据爬取、数据清洗、数据分析和数据可视化。我们将使用Python的requests、BeautifulSoup、pandas和matplotlib等库来实现这个任务。

爬取数据

首先,我们需要从当网上爬取书籍数据。我们可以使用Python的requests和BeautifulSoup库来实现这个任务。以下是一个简单的Python代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.dangdang.com/cp01.00.00.00.00.00.html'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

books = soup.find_all('div', {'class': 'con'})

data = []
for book in books:
    title = book.find('a', {'class': 'pic'}).get('title')
    author = book.find('div', {'class': 'publisher_info'}).find_all('a')[0].text
    price = book.find('span', {'class': 'price_n'}).text
    data.append([title, author, price])

df = pd.DataFrame(data, columns=['Title', 'Author', 'Price'])
print(df.head())

在上面的示例中,我们首先定义了一个url变量,它指向当网的书籍页面。然后,我们使用requests库发送一个HTTP请求,并使用BeautifulSoup库解析HTML响应。我们使用find_all方法找到HTML中的所有书籍元素,并使用find方法找到每个书籍元素中的标题、作者和价格。最后,我们将这些数据保存到一个列表中,并使用pandas库的DataFrame方法将其转换为DataFrame对象。最后,我们打印DataFrame对象的前几行,以检查数据是否正确。

数据清洗

接下来,我们需要对爬取到的数据进行清洗。我们可以使用pandas库来实现这个任务。以下是一个简单的Python代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.dangdang.com/cp01.00.00.00.00.00.html'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

books = soup.find_all('div', {'class': 'con'})

data = []
for book in books:
    title = book.find('a', {'class': 'pic'}).get('title')
    author = book.find('div', {'class': 'publisher_info'}).find_all('a')[0].text
    price = book.find('span', {'class': 'price_n'}).text
    data.append([title, author, price])

df = pd.DataFrame(data, columns=['Title', 'Author', 'Price'])

# 清洗价格数据
df['Price'] = df['Price'].str.replace('¥', '').astype(float)

print(df.head())

在上面的示例中,我们首先使用之前的代码爬取了数据,并将其转换为DataFrame对象。然后,我们使用str.replace方法将价格数据中的'¥'符号替换为空字符串,并使用astype方法将其转换为浮点数类型。最后,我们打印DataFrame对象的前几行,以检查数据是否正确。

数据分析

接下来,我们需要对清洗后的数据进行分析。我们可以使用pandas库来实现这个任务。以下是一个简单的Python代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.dangdang.com/cp01.00.00.00.00.00.html'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

books = soup.find_all('div', {'class': 'con'})

data = []
for book in books:
    title = book.find('a', {'class': 'pic'}).get('title')
    author = book.find('div', {'class': 'publisher_info'}).find_all('a')[0].text
    price = book.find('span', {'class': 'price_n'}).text
    data.append([title, author, price])

df = pd.DataFrame(data, columns=['Title', 'Author', 'Price'])

# 清洗价格数据
df['Price'] = df['Price'].str.replace('¥', '').astype(float)

# 统计每个作者的书籍数量和平均价格
author_count = df.groupby('Author').agg({'Title': 'count', 'Price': 'mean'})
print(author_count)

# 统计每个价格区间的书籍数量
price_bins = [0, 20, 40, 60, 80, 100, 200, 500]
price_labels = ['0-20', '20-40', '40-60', '60-80', '80-100', '100-200', '200-500']
df['Price Range'] = pd.cut(df['Price'], bins=price_bins, labels=price_labels)
price_count = df.groupby('Price Range').agg({'Title': 'count'})
print(price_count)

在上面的示例中,我们首先使用之前的代码爬取了数据,并将其转换为DataFrame对象。然后,我们使用str.replace方法将价格数据中的'¥'符号替换为空字符串,并使用astype方法将其转换为浮点数类型。接着,我们使用groupby方法对作者进行分组,并使用agg方法统计每个作者的书籍数量和平均价格。最后,我们使用cut方法将价格数据分成不同的价格区间,并使用groupby方法统计每个价格区间的书籍数量。

数据可视化

最后,我们可以使用matplotlib库将数据可视化。以下是一个简单的Python代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt

url = 'https://www.dangdang.com/cp01.00.00.00.00.00.html'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

books = soup.find_all('div', {'class': 'con'})

data = []
for book in books:
    title = book.find('a', {'class': 'pic'}).get('title')
    author = book.find('div', {'class': 'publisher_info'}).find_all('a')[0].text
    price = book.find('span', {'class': 'price_n'}).text
    data.append([title, author, price])

df = pd.DataFrame(data, columns=['Title', 'Author', 'Price'])

# 清洗价格数据
df['Price'] = df['Price'].str.replace('¥', '').astype(float)

# 统计每个价格区间的书籍数量
price_bins = [0, 20, 40, 60, 80, 100, 200, 500]
price_labels = ['0-20', '20-40', '40-60', '60-80', '80-100', '100-200', '200-500']
df['Price Range'] = pd.cut(df['Price'], bins=price_bins, labels=price_labels)
price_count = df.groupby('Price Range').agg({'Title': 'count'})

# 绘制饼图
plt.pie(price_count['Title'], labels=price_count.index, autopct='%1.1f%%')
plt.title('Number of books by price range')
plt.show()

在上面的示例中,我们首先使用之前的代码爬取了数据,并将其转换为DataFrame对象。然后,我们使用str.replace方法将价格数据中的'¥'符号替换为空字符串,并使用astype方法将其转换为浮点数类型。接着,我们使用cut方法将价格数据分成不同的价格区间,并使用groupby方法统计每个价格区间的书籍数量。最后,我们使用matplotlib库的pie方法绘制了饼图,并使用title方法设置图表的标题。最后,我们使用show方法显示图表。

示例2:爬取多页数据并进行数据可视化

以下是一个爬取多页数据并进行数据可视化的Python代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt

url_template = 'https://search.dangdang.com/?key=python&act=input&page_index={}'

data = []
for page in range(1, 6):
    url = url_template.format(page)
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    books = soup.find_all('li', {'class': 'line'})

    for book in books:
        title = book.find('a', {'class': 'pic'}).get('title')
        author = book.find('div', {'class': 'publisher_info'}).find_all('a')[0].text
        price = book.find('span', {'class': 'price_n'}).text
        data.append([title, author, price])

df = pd.DataFrame(data, columns=['Title', 'Author', 'Price'])

# 清洗价格数据
df['Price'] = df['Price'].str.replace('¥', '').astype(float)

# 统计每个价格区间的书籍数量
price_bins = [0, 20, 40, 60, 80, 100, 200, 500]
price_labels = ['0-20', '20-40', '40-60', '60-80', '80-100', '100-200', '200-500']
df['Price Range'] = pd.cut(df['Price'], bins=price_bins, labels=price_labels)
price_count = df.groupby('Price Range').agg({'Title': 'count'})

# 绘制柱状图
plt.bar(price_count.index, price_count['Title'])
plt.title('Number of books by price range')
plt.xlabel('Price Range')
plt.ylabel('Number of books')
plt.show()

在上面的示例中,我们首先定义了一个url_template变量,它包含一个占位符{},用于指定页码。然后,我们使用循环遍历页码,并使用format方法将页码插入到url_template中。我们使用requests和BeautifulSoup库爬取每一页的数据,并将其转换为DataFrame对象。接着,我们使用cut方法将价格数据分成不同的价格区间,并使用groupby方法统计每个价格区间的书籍数量。最后,我们使用matplotlib库的bar方法绘制了柱状图,并使用title、xlabel和ylabel方法来设置图表的标题、x轴标签和y轴标签。最后,我们使用show方法显示图表。

总结

本文详细讲解了如何使用Python爬虫爬取当网书籍数据并进行数据可视化展示的完整攻略,包括数据爬取、数据清洗、数据分析和数据可视化。我们提供了两个示例,以便更好地理解这些方法的使用。在实际应用中,我们可以根据需要选择适合自己的方法,以便更好地爬取数据并进行数据可视化展示。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python爬取当网书籍数据并数据可视化展示 - Python技术站

(0)
上一篇 2023年5月15日
下一篇 2023年5月15日

相关文章

  • Python列表list解析操作示例【整数操作、字符操作、矩阵操作】

    以下是详细讲解“Python列表list解析操作示例【整数操作、字符操作、矩阵操作】”的完整攻略。 整数操作 在Python中,使用列表解来对整数列表进行操作。例如,可以将一个整数列表中的所有元素加1,代码如下: numbers = [1, 2, 3, 4, 5] new_numbers = [x + 1 for x in numbers] print(ne…

    python 2023年5月13日
    00
  • Python实现switch/case语句

    使用Python实现Switch/Case语句是一种常见的需求,本文将提供两个不同的示例来说明如何实现。 示例一:使用字典实现Switch/Case语句 在Python中没有内置的Switch/Case语句,但是可以使用字典及函数的方式来实现同样的功能。 比如,我们要实现一个简单的计算器,支持加、减、乘、除操作。可以使用以下代码实现: def add(x, …

    python 2023年5月19日
    00
  • 详解python的循环

    下面是针对“详解Python的循环”的完整攻略。 详解Python的循环 在Python中,循环是一种非常强大的控制结构,让程序可以重复执行代码块。Python中有两种主要的循环结构:for循环和while循环。下面我们将详细讲解这两种循环的用法和示例。 for循环 for循环用于迭代一个可迭代对象(如一个列表或一个元组)中的每个元素,使得程序可以对每个元素…

    python 2023年6月5日
    00
  • python迭代器常见用法实例分析

    Python迭代器常见用法实例分析 什么是迭代器? 在Python中,迭代器是支持迭代的对象,实现了__iter__和__next__方法。其中__iter__方法返回实例自身,__next__方法返回序列中的下一个元素。当迭代到序列末尾时,迭代器会引发StopIteration异常。 Python中内置了很多迭代器,如range、list、tuple、se…

    python 2023年5月14日
    00
  • 8种用Python实现线性回归的方法对比详解

    8种用Python实现线性回归的方法对比详解 线性回归是机器学习中的一个重要问题,Python可以很方便地实现这个操作。本文将介8种用Python实现线性回归的方法,并对它们进行详细对比。 1. 基本思路 线性回归是一用于建立两个变量之间线性关系的方法。在Python中,我们可以使用numpy和scikit-learn库来实现线性回归。具体实现如下: imp…

    python 2023年5月14日
    00
  • Python语法学习之进程池与进程锁详解

    Python语法学习之进程池与进程锁详解 进程池 在Python中,可以通过multiprocessing模块来实现多进程的编程。当我们需要创建多个进程的时候,就需要使用到进程池。 进程池的使用 要使用Python中的进程池,可以使用multiprocessing.Pool类来创建进程池。具体的使用方法如下: from multiprocessing imp…

    python 2023年5月19日
    00
  • python实现猜拳游戏

    Python实现猜拳游戏 一. 游戏规则 猜拳游戏是一种非常受欢迎的游戏,它的规则如下: 石头、剪刀、布三种手势,石头胜剪刀,剪刀胜布,布胜石头; 玩家和电脑各出一种手势,通过比较手势的胜负来决定胜负; 相同手势为平局,需要重新出拳; 游戏设置三局两胜,其中玩家和电脑分别累计胜利数,先达到两胜者获胜。 二. 实现步骤 实现猜拳游戏的步骤如下: 引用rando…

    python 2023年6月3日
    00
  • Python中4种实现数值的交换方式

    下面是Python中4种实现数值的交换方式的完整攻略。 一、使用第三个变量 使用第三个变量是最朴素的交换方式,先将一个变量的值保存到第三个变量中,再将第二个变量的值赋给第一个变量,最后将第三个变量的值赋给第二个变量。示例代码如下: a = 1 b = 2 c = a a = b b = c print(a, b) # 输出2, 1 二、使用加法和减法 使用加…

    python 2023年5月13日
    00
合作推广
合作推广
分享本页
返回顶部