无法处理列表索引错误

Trouble handling list index error

只要我从打印语句中排除 phone 号码,我编写的用于解析黄页中的姓名、地址和 phone 号码的脚本就可以正常工作。 如果我尝试打印其中三个,它会抛出显示 "list index out of range" 的错误。我自己找不到补救措施。这是我到目前为止尝试过的方法。

import requests
from bs4 import BeautifulSoup

url=requests.get("https://www.yellowpages.com/search?search_terms=Coffee%20Shops&geo_location_terms=San%20Francisco%2C%20CA&page=1")
soup=BeautifulSoup(url.text,'lxml')
for item in soup.findAll(class_="info"):
    name=item.findAll(class_="business-name")[0].text
    address=item.findAll(class_="adr")[0].text
    # phone=item.findAll(class_="phones")[0].text
    # print(name,phone,address)
    print(name,address)

Link 亚当爵士:“https://www.dropbox.com/s/pt9yk6y5zu9r0ag/For%20sir%20adam.txt?dl=0

当 selecting namephoneaddress 时,最好使用 find,其中 returns 只有第一个匹配而不是findAll 其中 returns 所有匹配的列表。

关于您的问题,soup.findAll(class_="info") 中的第一项没有 'phones' 标记,因此 item.findAll returns 是一个空列表,当您尝试 select 第一项。

您可以使用 try - except 或 if - else 块来处理这种情况。例如:

for item in soup.findAll(class_="info"):
    name=item.find(class_="business-name").text
    address=item.find(class_="adr").text
    phone=item.find(class_="phones").text if item.find(class_="phones") else None
    print(name,phone,address)

或者如果你坚持使用 findAll :

phone=item.findAll(class_="phones")[0].text if item.findAll(class_="phones") else None

使用函数:

def if_exist(item, item_class):
    pro=item.find(class_=item_class)
    if pro:
        return pro.text
    return ""

示例:

phone=if_exist(item, "phones")
import requests
from bs4 import BeautifulSoup

url=requests.get("https://www.yellowpages.com/search?search_terms=Coffee%20Shops&geo_location_terms=San%20Francisco%2C%20CA&page=1")
soup=BeautifulSoup(url.text,'lxml')

if __name__ == '__main__':
    for item in soup.findAll(class_="info"):
        name=item.findAll(class_="business-name")[0].text
        address = item.findAll(class_="adr")[0].text if len(item.findAll(class_="adr")) else 'No Address' 
        phone = item.findAll(class_="phones")[0].text if len(item.findAll(class_="phones")) else 'No Phones'
        print(name,phone,address)