某些desc
项可能为空。这就是csv为空的原因吗?如何使其忽略并继续打印?
try:
name = div.find_element_by_class_name('styles_itemNameText__3bcKX')
price = div.find_element_by_class_name('rupee')
desc = div.find_element_by_class_name('styles_itemDesc__MTsVd')
dict1 = {'Item Name': name.text, "Price": price.text, "Description": desc.text}
with open(f'{search_city}_{res_n}.csv', 'a+', encoding='utf-8') as f:
w = csv.DictWriter(f, dict1.keys())
if not header_added:
w.writeheader()
header_added = True
w.writerow(dict1)
except:
try:
name = div.find_element_by_class_name('styles_itemNameText__3bcKX')
price = div.find_element_by_class_name('rupee')
# What i added
if div.find_elements_by_class_name('styles_itemDesc__MTsVd'):
desc = div.find_element_by_class_name('styles_itemDesc__MTsVd').text
else:
desc = None
dict1 = {'Item Name': name.text, "Price": price.text, "Description": desc}
with open(f'{search_city}_{res_n}.csv', 'a+', encoding='utf-8') as f:
w = csv.DictWriter(f, dict1.keys())
if not header_added:
w.writeheader()
header_added = True
w.writerow(dict1)
except:
使用if语句根据条件设置desc
的值。