如果处理了错误,While循环将跳过一个循环.我怎样才能让它在循环的剩余时间里运行



我还是Python的新手,我写了一些代码来帮助我浏览一些在线列表。

我不得不在那里进行一些错误处理,因为如果找不到列表的属性,就会导致程序崩溃。

如果我尝试使用pass或continue,我就会陷入一个无限循环,正如预期的那样。

我觉得自己陷入了困境,似乎找不到解决办法。我发现的解决方案我无法理解,大多数都是针对其他语言的。

我如何才能做到这一点,这样一旦发现错误,循环就不会跳过所有其他属性?

编辑:我想我的帖子在这一点上不清楚,我很抱歉。结果是:如果在列表中找不到感兴趣的元素,则跳过其他元素。因此,如果列表中没有指定所有者名称(第一个元素或属性(,那么整个列表将被忽略。它继续到下一个列表。你知道我该怎么解决吗?

这是代码的一部分:

#iterate through the results according to user input earlier
i = 0
while (i < number_of_results):
Result_page = driver.current_url
#define elements of the listing of interest
stran = requests.get(driver.current_url)
soup = BeautifulSoup(stran.content, 'html.parser')
ime = soup.find("dd", itemprop="name")
ulica = soup.find("dd", itemprop="streetAddress")
postna_stevilka = soup.find("span", itemprop="postalCode")
kraj = soup.find("span", itemprop="addressLocality")
tel = soup.find("dd", itemprop="telephone")
spletna_stran = soup.find("dd", itemprop="url") 
mobil = soup.find("a", itemprop="telephone")

try:
print(ime.text)
c1 = sheet.cell(row=i+1, column=1)
c1.value = ime.text
print(ulica.text)
c1 = sheet.cell(row=i+1, column=2)
c1.value = ulica.text
print(postna_stevilka.text)
c1 = sheet.cell(row=i+1, column=3)
c1.value = postna_stevilka.text
print(kraj.text)
c1 = sheet.cell(row=i+1, column=4)
c1.value = kraj.text
print(tel.text)
c1 = sheet.cell(row=i+1, column=5)
c1.value = tel.text
#print(mobil.text) does not work, cut out to prevent error
print(spletna_stran.text)
c1 = sheet.cell(row=i+1, column=6)
c1.value = spletna_stran.text


#catch the error when an entry isn't there      
except AttributeError:
print("No such entry.")



next_entry = driver.find_element_by_xpath("/html/body/main/chousingdetail/div/div[2]/div[1]/nav/div/div[2]/a[2]/i")
next_entry.click()
i +=1

如果我正确理解您要做的事情,那么您不应该那样使用try...except

一旦try块遇到异常,它就会跳到except块中。它不会";尝试";其余的线路。因此,如果您希望检查所有元素,而不管它们中的任何一个失败,您需要将它们中的每一个放在单独的try...except块中。例如,

try:
print(ime.text)
c1 = sheet.cell(row=i+1, column=1)
c1.value = ime.text
except:
pass
try:
print(ulica.text)
c1 = sheet.cell(row=i+1, column=2)
c1.value = ulica.text
except:
pass

依此类推。这样,就会处理丢失的值,并且脚本只会移动到下一个元素。

然而,我更喜欢这样做:因为如果bs4.BeautifulSoup.find()找不到任何东西,它就会返回None,所以可以使用:

ime = soup.find("dd", itemprop="name")
if ime:
print(ime.text)
c1 = sheet.cell(row=i+1, column=1)
c1.value = ime.text

等等。我甚至会把这些行封装在一个函数中,因为它们对每个元素几乎都是一样的。(事实上,我可以对你的代码提出一些改进建议,但也许这是另一次讨论;我现在会坚持这个问题!(

复制粘贴finally语句内的最后三行。

最新更新