我的代碼工作正常,但PyCharm在下面提到的except
子句太寬泛。說實話,它也聞到了我的錯誤實現。Python:我的除外條款確實太寬泛了嗎?
當我拼湊HTML <tr>
時,我也必須添加到數據庫或更新,但事先並不知道遊戲是否完成。此外,尚未完成的遊戲在某些<td>
中有不同的HTML標籤,需要不同的處理。
基本上,如果我們看看match_score_string
和match_relevant_bit
,我們告訴BeautifulSoup找到一個具有某個類別的<td>
。如果遊戲已經完成,這個<td>
將有一個score-time sc
類,如果沒有,它將有一個score-time st
類。如果它有一個,它就不會有另一個。
自從我編寫try-except
子句以來已經有一段時間了,但是如果我記得正確的話,我必須使用它的原因是因爲當row.find
無法找到HTML時,BS會拋出錯誤並暫停所有操作目的。
PyCharm抱怨是否合理?
# Get Match Score
try:
match_score_string = row.find("td", class_="score-time sc").get_text()
match_string_split = match_score_string.split(" - ")
team_a_score = int(match_string_split[0])
team_b_score = int(match_string_split[1])
print(team_a_score)
print(team_b_score)
except:
team_a_score = None
team_b_score = None
# Get Match URL
try:
match_relevant_bit = row.find("td", class_="score-time sc")
match_url = match_relevant_bit.find("a").get("href")
match_url_done = match_url.rsplit('?JKLMN')
match_url = match_url_done[0]
match_finished = True
except:
match_relevant_bit = row.find("td", class_="score-time st")
match_url = match_relevant_bit.find("a").get("href")
match_url_done = match_url.rsplit('?JKLMN')
match_url = match_url_done[0]
match_finished = False
另一種情況是'sys.exit()'在這種嘗試中調用時不起作用,除了塊 –
@JossefHarush - 當然。或者失敗的'assert'語句或......任何東西。 :-) – mgilson
您會如何處理外部異常,比如'KeyboardInterrupt'或任何'RuntimeError',而不是專門處理'try'子句中的代碼引發的異常?傳統的異常處理是處理'try'中的「直接」錯誤(比如'find'或者一個不可能的'int'類型),似乎OP想要以同樣的方式處理所有這些異常,但正如你寫的那樣,外部異常例如'KeyboardInterrupt'應該被不同的處理。 –