python - 在数周内抓取时列出超出范围的索引
问题描述
从 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
解决方案
您正在尝试索引列表而不检查列表是否为空。您必须重写 getData() 以确保当您调用soup.find_all() 时不会得到一个空列表,并在您这样做时按照您的意愿处理该错误。还要确保你想要访问的元素在你正在解析的地方。
推荐阅读
- mysql - 如何在 ubuntu18 中将 lower_case_table_names=1 恢复为 lower_case_table_names=0(默认)
- tensorflow - 损失函数包装在 keras 中工作,但不适用于 tf.keras
- node.js - Sequelize - 使用自定义 where 获取所有数据
- python - Pandas_Unable 将所有行写入 Excel 工作表
- javascript - Eslint + Prettier + React。道具缩进
- javascript - 将数据添加到外部 javascript 文件中的数组
- javascript - 如何从JSON动态地在图表js中添加多个数据
- javascript - 在 JavaScript Discord Bot 中,为什么 message.react() “不是函数”
- vue.js - VueJS - 如何在 axios 中设置根证书
- reactjs - AntTable React - 无法通过 rowClassName 设置行边框