首页 > 解决方案 > 在数周内抓取时列出超出范围的索引

问题描述

从 1958 年到 2021 年,我一直在尝试每周抓取 Billboard 的前 100 名排行榜,但我遇到了问题。我想知道这首歌的名称、艺术家、它在排行榜上的周数以及从 1958 年 8 月到 2021 年 7 月在前 100 名排行榜中的每首 #1 歌曲的年份。我已经定义了一个函数来获取该信息对于(特定周的)给定链接,然后我使用 for 循环每周重复该过程(我已将每周的周期链接存储在列表中)但我得到 Index Error: list index out of Range同时这样做。所有网站都具有相同的 HTML 结构,所以我认为问题不存在,但我一直在重复 for 循环,而且我并不总是从网站获得相同的信息(即,我可能会在 1960 年之前得到相同的信息,然后再试一次可能会在 1975 年之前获得信息),这让我感到困惑。如果有人知道可能是什么问题并想帮助我,我将不胜感激。代码如下:


base_url = "https://www.billboard.com/charts/hot-100/{}"

start_date = datetime(1958, 8, 2)
end_date = datetime(2021, 7, 10)
one_week = timedelta(days=7)

links = []
while start_date <= end_date:
  url_ = base_url.format(start_date.strftime("%Y-%m-%d"))
  links.append(url_)
  start_date += one_week

song = []
art = []
weeks = []
year = []
dicc = {'Song': song, 'Artist': art, 'Weeks_on_chart': weeks, 'Year': year}
def getdata(url):  
    r = requests.get(url, headers= headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    song.append(soup.find_all('span', {'class': 'chart-element__information__song text--truncate color--primary'})[0].get_text())
    art.append(soup.find_all('span', {'class': 'chart-element__information__artist text--truncate color--secondary'})[0].get_text())
    weeks.append(soup.find_all('span', {'class': 'chart-element__meta text--center color--secondary text--week'})[0].get_text())
    year.append(soup.find_all('button',{'class': 'date-selector__button button--link'})[0].get_text().split()[2])

for element in links: #repeat for every link (every week)
  getdata(element)    #here is where List index out of Range pops (lists from function getdata)


df = pd.DataFrame(dicc)
df #just to visualize until which year I could get info

标签: pythonweb-scraping

解决方案


您正在尝试索引列表而不检查列表是否为空。您必须重写 getData() 以确保当您调用soup.find_all() 时不会得到一个空列表,并在您这样做时按照您的意愿处理该错误。还要确保你想要访问的元素在你正在解析的地方。


推荐阅读