以代码中info1_list为横轴,count_list为相应数据,以200,400,600,800为纵轴,绘制柱形图import requests from bs4 import BeautifulSoup import matplotlib.pyplot as plt import numpy as np headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41'} url='https://www.ibiquges.com/xiaoshuodaquan/' strhtml=requests.get(url,headers=headers) soup=BeautifulSoup(strhtml.text,'lxml') info_list = []#书籍目录 count_list = []#书籍数量 info1_list = [] for i in range(1, 14, 2): info = soup.select(f'#main > div:nth-child({i}) > ul') info1 = soup.select(f'#main > div:nth-child({i}) > h2') for item in info: #print(item.get_text()) count = len(info[0].find_all('li')) count_list.append(count) info_list.append(info) for item1 in info1: print(item1.get_text()) info1_list.append(item1.get_text()) print(info1_list) print(count_list)
时间: 2024-04-04 13:29:24 浏览: 139
可以使用Matplotlib库中的pyplot模块来绘制柱形图,代码如下:
```
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import numpy as np
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41'}
url='https://www.ibiquges.com/xiaoshuodaquan/'
strhtml=requests.get(url,headers=headers)
soup=BeautifulSoup(strhtml.text,'lxml')
info_list = []#书籍目录
count_list = []#书籍数量
info1_list = []
for i in range(1, 14, 2):
info = soup.select(f'#main > div:nth-child({i}) > ul')
info1 = soup.select(f'#main > div:nth-child({i}) > h2')
for item in info:
count = len(info[0].find_all('li'))
count_list.append(count)
info_list.append(info)
for item1 in info1:
info1_list.append(item1.get_text())
# 以info1_list为横轴,count_list为纵轴,绘制柱形图
x = np.array(info1_list)
y = np.array(count_list)
fig, ax = plt.subplots()
ax.bar(x, y)
# 设置纵轴坐标范围
ax.set_ylim([0, 1000])
# 设置纵轴刻度
ax.set_yticks([200, 400, 600, 800])
# 添加网格线
ax.grid(True)
# 添加标题和标签
ax.set_title('Books Count')
ax.set_xlabel('Book Info')
ax.set_ylabel('Count')
plt.show()
```
运行代码后,将会得到一个柱形图,其中info1_list为横轴,count_list为纵轴,纵轴坐标范围为0-1000,纵轴刻度为200,400,600,800。
阅读全文