首页 > 解决方案 > 我的脚本没有抓取所有 Yelps 餐厅

问题描述

我的脚本在第 449 家 Yelp 餐厅后停止抓取。

完整代码:https ://pastebin.com/5U3irKZp

for idx, item in enumerate(yelp_containers, 1):
    print("--- Restaurant number #", idx)
    restaurant_title = item.h3.get_text(strip=True)
    restaurant_title = re.sub(r'^[\d.\s]+', '', restaurant_title)
    restaurant_address = item.select_one('[class*="secondaryAttributes"]').get_text(separator='|', strip=True).split('|')[1]

我得到的错误是:

Traceback(最近一次通话最后):文件“/Users/kenny/MEGA/Python/yelp scraper.py”,第 41 行,位于 restaurant_address = item.select_one('[class*="secondaryAttributes"]').get_text(separator ='|', strip=True).split('|')[1] IndexError: 列表索引超出范围

标签: pythonbeautifulsoup

解决方案


问题是一些餐馆缺少地址,例如这个:

在此处输入图像描述

您应该首先检查地址是否有足够的元素,然后再对其进行索引。更改这行代码:

restaurant_address = item.select_one('[class*="secondaryAttributes"]').get_text(separator='|', strip=True).split('|')[1]

对这些:

restaurant_address = item.select_one('[class*="secondaryAttributes"]').get_text(separator='|', strip=True).split('|')
restaurant_address = restaurant_address[1] if len(restaurant_address) > 1 else restaurant_address[0]

我为所有页面运行了你的解析器,它工作正常。


推荐阅读