def singers_band_info(url, pagetext):
get_soup = lambda page:BeautifulSoup(page, 'html.parser')
get_rows = lambda soup:soup.find_all("tr")
get_cols = lambda row:row.find_all("th") + row.find_all("td")
get_colstd = lambda row:row.find_all("td")
rows = get_rows(get_soup(pagetext))
for row in rows:
cols = get_cols(row)
colstd = get_colstd(row)
if cols[0].get_text() == "Born":
try:
born = colstd[0].get_text()
born = born[1:11]
except:
born = "False"
if cols[0].get_text() == "Years active":
try:
ya = colstd[0].get_text()
except:
ya = "False"
if cols[0].get_text() == "Genres":
try:
genres = colstd[0].get_text()
except:
genres = "False"
singer_band_info_d = dict(url = url, genres = genres, born = born, ya = ya)
return singer_band_info_d
答案 0 :(得分:0)
如果您收到该错误,则只表示您调用或尝试分配不存在的变量。
要解决此问题,请在函数定义之前添加born = ""
。
作为一种检查的好方法,您可以为变量born
提供默认分配,例如"Something went wrong."
或0
。然后在函数完成执行之前打印出变量。如果它被卡在那里,那么你知道问题出在try/excepts.
答案 1 :(得分:0)
您在born
循环内分配for row in rows
变量。这个问题是可能没有行,因此没有born
赋值。
在此循环之前放置born = "False"
。