python 和 csv 如果变量为空如何传递?

python and csv how to pass if variable is empty?

    with open('test.csv', 'a', newline='', encoding='utf-8-sig',) as file:
        writer = csv.writer(file)
        writer.writerow([driver.current_url])
        all_data = [item_1.text, item_2.text, item_3.text, item_4.text,
                    item_5.text,item_6.text, item_7.text, item_8.text,
                    item_9.text, item_10.text,]
        filtered_strings = [string for string in all_data if string != ""]
        writer.writerow(filtered_strings)

错误:UnboundLocalError:赋值前引用局部变量'item_31'

我使用 selenium 来查找元素,而不是将每个元素分配给变量,但有时脚本没有获取数据,我得到了错误。即使我已经将它分配给变量,如果没有数据我怎么能忽略?

使用 Try 和 catch 块来捕获异常。

try:
  your code
except:
  print("An exception catched")

要了解 try catch 块,您可以参考下面的内容 link https://www.w3schools.com/python/python_try_except.asp