您正在使用 Selenium 和 BeautifulSoup 从多个网页中提取数据,其中一些网页具有不同的 HTML 格式。当您处理其中一个具有不同格式的网页时,遇到了一次 AttributeError 异常。您希望用代码实现以下功能:当遇到该异常后,能够尝试执行其他代码,然后从异常发生处继续执行程序。
price = soup.find('li', {'id' :'J_PromoPrice'})
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
if priced == "":
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
else:
print ("No Normal Price Found")
这个代码包含了一个 if-else 语句,用于检测 priced
是否为空。如果它为空,则会尝试使用另一个标签来查找文本,以处理两种不同的 HTML 格式。然而,对于第三种 HTML 格式,它甚至没有找到这个标签,而是在其他位置找到了这个标签。因此,您希望在遇到 AttributeError 异常时,能够从其他位置获取文本,然后继续执行程序。
-
解决方案:
您可以使用 try-except 语句块来实现这个功能。try-except 语句块可以用来捕获异常,并执行相应的异常处理逻辑。在您的情况下,您可以使用如下代码:price = soup.find('li', {'id' :'J_PromoPrice'}) try: priced = price.find('strong', {'class' :'tb-rmb-num'}).text if priced == "": priced = price.find('strong', {'class' :'tb-rmb-num'}).text else: print ("No Normal Price Found") except AttributeError: # 在这里执行异常处理代码 # 例如,尝试从其他位置获取文本
当程序执行到 try 块中的代码时,如果发生 AttributeError 异常,程序就会执行 except 块中的代码。在 except 块中,您可以尝试执行其他代码,以从其他位置获取文本。
下面提供一个简单的代码示例,演示了如何使用 try-except 语句块来捕获 AttributeError 异常:
try: # 尝试执行可能发生 AttributeError 异常的代码 value = None value.text except AttributeError: # 如果发生 AttributeError 异常,则执行异常处理代码 print("Value is None, cannot access its text attribute.")
当您运行这段代码时,程序会输出 “Value is None, cannot access its text attribute.”,因为变量
value
为 None,并且您尝试访问它的text
属性,从而导致 AttributeError 异常。在您的具体场景中,您可以在 except 块中添加代码,以从其他位置获取文本,并继续执行程序。例如,您可以添加如下代码:
except AttributeError: # 尝试从其他位置获取文本 priced = soup.find('strong', {'class' :'tb-rmb-num-2'}).text if priced == "": priced = soup.find('strong', {'class' :'tb-rmb-num-3'}).text else: print ("No Normal Price Found")
这段代码会尝试从其他两个标签中获取文本,如果这些标签中也没有文本,则会打印 “No Normal Price Found”。您还可以根据您的实际需求,添加其他异常处理逻辑。