【问题标题】:How I write exceptions in python if no results are found when looking up information?如果在查找信息时没有找到结果,我如何在 python 中编写异常?
【发布时间】:2019-08-05 04:38:41
【问题描述】:

我正在使用 for 循环输入信息来遍历数据框。每次输入信息。姓名和身份证。如果存在,数据库将返回信息,否则将不返回任何信息。没有信息返回时如何编写异常。

mylist=[]
for i,j in df1.iterrows():
    name = j[1]
    age = j[2]
    sleep(3)
    n = input(name)
    a = input(age)
    mylist1=[]
    result1= driver.find_element_by_css_selector("height")
    result2 = driver.find_element_by_css_selector("id")
    mylist1.append("height: ",result1)
    mylist1.append("id: ",result2)

print(tokens)

【问题讨论】:

  • 你能提供一个样本吗,那里不会有信息?
  • 你的意思是引发异常还是使用try/except?
  • @bumblebee 我正在使用 selenium webscraper 输入带有 ID 号的名称。此信息在 df.xml 中。输入name和id时,如果name和id在数据库中存在则返回信息,如果不存在则什么都不显示。
  • selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:

标签: python for-loop exception try-catch writetofile


【解决方案1】:

在for loop之后,你可以这样做

if not mylist:
    raise Exception('The error message')

但是提出这样的通用异常被认为是一种不好的做法,应该避免。相反,您应该使用语义上适合您的问题的最具体的构造函数,所以我建议

if not mylist:
    raise ValueError('The error message')

更多详情您可以访问link

【讨论】:

  • selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:
  • @我只是希望它通过并移动到列表中的下一个名称。
  • 所以我认为你可以尝试一下:# 生成异常异常的代码:继续,但这是一种不好的做法,应该避免
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多