python - 如果处理了错误,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
等等。我什至会将这些行包装在一个函数中,因为它们对于每个元素几乎都是相同的。(事实上,我可以对您的代码提出一些改进建议,但也许这是另一个讨论;我现在会坚持这个问题!)
推荐阅读
- snowflake-cloud-data-platform - 复制到脚本以复制多个表并用于日常运行
- node.js - 等待 Electron 窗口成为特定的 URL?
- r - 在 R 中读取目录中的特定文件
- ios - 在 ios 中弹出到下一个 viewController
- python - fit() 到底在这里做什么?
- r - 使用 Rglpk 最小化简单函数
- python - Python 类垃圾收集时调用的方法
- javascript - 使用 Filesaver.js 的 D3JS 图形无法导出 Font Awesome 图标
- sleep - 使用 [nohup ksh] 运行脚本看不到睡眠进程
- systemtap - Systemtap (stap) 探测失败并显示“此语句可能会通过 [-Werror=implicit-fallthrough=]”