I have a bunch of statements I want to use try, except on. Yes bad practise.
There must be a more pythonic way to write the following?
try:
E1=clean_html.find("span",{"class":"range-a"}).text
except AttributeError:
E1=None
try:
E2=clean_html.find("span",{"class":"range-b"}).text
except AttributeError:
E2=None
try:
E3=clean_html.find("span",{"class":"range-c"}).text
except AttributeError:
E3=None
try:
E4=clean_html.find("div",{"class":"Description"}).get_text(separator=" ").strip()
except AttributeError:
E4=None
Because this code works fine for me, but it looks unefficient.
You can assign a default to the variables and then do the work. Since you want the default to be the immutable None
, you can
E1 = E2 = E3 = E4 = None
try:
E1=clean_html.find("span",{"class":"range-a"}).text
E2=clean_html.find("span",{"class":"range-b"}).text
E3=clean_html.find("span",{"class":"range-c"}).text
E4=clean_html.find("div",{"class":"Description"}).get_text(separator=" ").strip()
except AttributeError:
pass
The best way to handle exceptions depends on more context than we have here, but generally you want to write larger blocks that stay in a sane state on any "exceptional" operation.
Since exceptions take some processing power to setup and may be visually untidy, testing (especially when wrapped in its own function) can be a better way to go.
def get_elem_text(elem, default=None):
if elem:
return elem.text
else:
return default
E1=get_elem_text(clean_html.find("span",{"class":"range-a"}))
E2=get_elem_text(clean_html.find("span",{"class":"range-b"}))
E3=get_elem_text(clean_html.find("span",{"class":"range-c"}))
# I don't know what "get_text" is so can't abstract it
#E4=get_elem_text(clean_html.find("div",{"class":"Description"}), default="")).strip()
You can write a function that handles the try and except. You can pass the post_processing as a lambda if you want the function to handle the problem of None throwing errors when calling methods on it
def get_clean_text(tag, class_name, post_processor):
try:
return post_processor(clean_html.find(tag,{"class": class_name}))
except AttributeError:
return None
E1 = get_clean_text("span", "range-a", lambda o: o.text)
E4 = get_clean_text("div", "Description", lambda o: o.get_text(separator=" ").strip())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.