nobody-梁 2022-06-09 16:12 采纳率: 100%
浏览 58
已结题

图表画不出来,出现list index out of range

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
import re
import pandas as pd
import lxml.html
import requests
from PIL import Image
from io import BytesIO
from selenium.webdriver.common.by import By

opt = Options()
opt.add_experimental_option('excludeSwitches', ['enable-automation'])
opt.add_argument('--disable-blink-features')
opt.add_argument('--disable-extensions')
opt.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(options=opt) # 创建driver对象
driver.get('https://www.douyu.com/')  #打开页面
time.sleep(5)
a=driver.find_element(By.XPATH,'//h2[@class="layout-Module-title"]/a')
a.click()
time.sleep(2)
driver.switch_to.window(driver.window_handles[-1])  #读取新页面
html=driver.page_source
driver.close()  #关闭页面


xp=lxml.html.fromstring(html)     #lxml对象
units=xp.xpath('//li[@class="layout-Cover-item"]')   #没有text()
df=pd.DataFrame()

df = None
volume=[]
title=[]

for u in units:
    t={}
    t['标题']=u.xpath('./div/a/div[2]/div/h3[@class="DyListCover-intro"]/text()')[0]
    t['主播']=u.xpath('./div/a/div[2]/div[@class="DyListCover-info"]/h2[@class="DyListCover-user"]')[0].xpath('string()')
    t['播放量']=u.xpath('./div/a/div[2]/div[@class="DyListCover-info"]/span[@class="DyListCover-hot"]/text()')[0]

    if t['标题'] ==[]:
        print('无')
    df1=pd.DataFrame([t])
    df = pd.concat([df,df1], ignore_index=True)

    b= re.findall(r'\d+[.]\d+',t['播放量'])[0]
    print(b)
    volume.append(float(b))
    title.append(t['标题'])
    if len(df)>80:
        break
print(df)
print(df.dtypes)

import pandas as pd
df = pd.DataFrame({'播放量':volume}, index=title)
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
pd.to_numeric(df['播放量']).plot(kind='bar')
plt.show()





  • 写回答

1条回答 默认 最新

  • 请叫我问哥 Python领域新星创作者 2022-06-09 16:27
    关注

    因为正则式没有找到内容。
    你的正则式里必须要匹配小数点,但是如果播放量没有小数点,就找不到了,自然也就报错了
    b= re.findall(r'\d+[.]\d+',t['播放量'])[0]

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 6月17日
  • 已采纳回答 6月9日
  • 创建了问题 6月9日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)