【问题标题】:How to fix Webscraping IndexError如何修复 Webscraping IndexError
【发布时间】:2019-01-14 00:32:12
【问题描述】:

我正在尝试将 IFPI 2014 数据的数据放入 csv 文件中。但是我不断收到此索引错误。


Traceback(最近一次调用最后一次): 文件“C:\Users\Brian\eclipse-workspace\FTS\src\FirstModule.py”,第 15 行,在 tbody = soup('table', {"class":"wikitable plainrowheaders sortable jquery-tablesorter"})[0].find_all('tr') IndexError: 列表索引超出范围


我注意到 csv 文件已创建,但 csv 文件中没有数据。我不明白为什么它会给我这个错误消息,因为据我了解索引是正确的。

import csv
import urllib.request
from bs4 import BeautifulSoup

f = open('dataoutput.csv', 'w', newline = '')
writer = csv.writer(f)
soup = BeautifulSoup(urllib.request.urlopen("https://en.wikipedia.org/wiki/Global_music_industry_market_share_data").read(), 'lxml')

tbody = soup('table', {"class":"wikitable plainrowheaders sortable 
jquery-tablesorter"})[0].find_all('tr')
for row in tbody:
    cols = row.findChildren(recursive=False)
    cols = [ele.text.script() for ele in cols]
    writer.writerow(cols)
    print(cols)

谁能指出我哪里出错了。

【问题讨论】:

    标签: python


    【解决方案1】:

    由于您是通过 REST 请求获取页面,因此没有添加任何 css 或 js 属性。 以下代码 sn-p 正在为我返回数据:

    tbody = soup('table', {"class":"wikitable plainrowheaders sortable"})[0].find_all('tr')
    

    【讨论】:

      猜你喜欢
      • 2019-09-14
      • 2019-12-09
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2021-11-08
      • 1970-01-01
      • 2019-11-25
      相关资源
      最近更新 更多