0

我编写了一个 Python 脚本,用于抓取页面中的电话号码、地址、评级等信息。当页面上的所有值都可用时,该脚本运行良好。但是,如果没有特定信息(例如电话号码不可用),则会引发错误。它打破了循环,我想要的只是跳过这些页面并继续抓取下一页。

以下是提取电话号码的示例代码:

def get_phone_number(body):
i=0
for item in body.find('p',{'class':'contact-info'}):
    i+=1
    if(i==2):
        phoneNo=''
        try:
            for element in item.find_all(class_=True):
                classes = []
                classes.extend(element["class"])
                phoneNo+=str((which_digit(classes[1])))
        except:
            pass
        return phoneNo

以上是抓取联系信息的功能。以下是我在 for 循环中面临的错误。

TypeError                                 Traceback (most recent call last)
<ipython-input-30-bfd4a9d231f1> in <module>()
     20                 dict_service = {}
     21                 name = get_name(service_html)
---> 22                 phone = get_phone_number(service_html)
     23                 rating = get_rating(service_html)
     24                 count = get_rating_count(service_html)

<ipython-input-25-7168fec7d0c7> in get_phone_number(body)
     21 def get_phone_number(body):
     22     i=0
---> 23     for item in body.find('p',{'class':'contact-info'}):
     24         i+=1
     25         if(i==2):

TypeError: 'NoneType' object is not iterable

任何形式的帮助将不胜感激!

4

2 回答 2

1

当您尝试迭代 None 对象时,您会收到此错误。这条线

for element in item.find_all(class_=True):

不会是引发异常的地方,因为它已被处理。可能发生此错误的行在try ... except块之外。很可能是以下行

for item in body.find('p',{'class':'contact-info'}):

要处理此问题,您应该防止在 NoneType 上进行迭代。你有两个选择。

使用try.... except块。

try:
    for item in body.find('p',{'class':'contact-info'}):
        i+=1
        if(i==2):
            phoneNo=''
            try:
                for element in item.find_all(class_=True):
                    classes = []
                    classes.extend(element["class"])
                    phoneNo+=str((which_digit(classes[1])))
            except:
                pass
            return phoneNo
except:
    pass

使用条件分支

items = body.find('p',{'class':'contact-info'})

if items is not None:
    for item in items:
        i+=1
        if(i==2):
            phoneNo=''
            try:
                for element in item.find_all(class_=True):
                    classes = []
                    classes.extend(element["class"])
                    phoneNo+=str((which_digit(classes[1])))
            except:
                pass
            return phoneNo
于 2018-12-27T06:44:20.723 回答
0

find 方法不返回可迭代对象或类似对象的列表。您使用了 find_all 方法,例如

for item in body.find_all('p'):
于 2018-12-27T06:51:39.507 回答