我正在练习刮的网页-‘罗顿番茄’使用美丽汤。然而,我遇到了一个问题,似乎并不是所有的电影都有box_office号或运行时,所以当我尝试运行我的代码时,会有一个"AttributeError",上面写着'NoneType‘。有什么方法可以绕过电影中的'box_office’或这个错误呢?
谢谢!
df_list1 = []
for movie_html in os.listdir(folder):
with open(os.path.join(folder, movie_html)) as file:
soup = BeautifulSoup(file,'lxml')
release_date = soup.find_all('div', class_='meta-value')[4].find('time').contents[0]
box_office = soup.find_all('div', class_='meta-value')[6].contents[0].replace('$','').replace(',','')
runtime = soup.find_all('div', class_='meta-value')[7].find('time').contents[0].strip()[:-len(" minutes")]
studio = soup.find_all('div', class_='meta-value')[8].find('a').contents[0]
df_list.append({[![enter image description here][1]][1]
'box_office':box_office,
'run_time': int(runtime),
'studio':studio
})
[1]: https://i.stack.imgur.com/yopG5.png发布于 2021-04-22 21:16:29
您需要的是试一试--除了块:
try:
box_office = soup.find_all('div', class_='meta-value')[6].contents[0].replace('$','').replace(',','')
except AttributeError:
box_office = None在python 错误和异常处理异常中阅读更多内容
https://stackoverflow.com/questions/67220761
复制相似问题