python - 我的脚本没有抓取所有 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: 列表索引超出范围
解决方案
问题是一些餐馆缺少地址,例如这个:
您应该首先检查地址是否有足够的元素,然后再对其进行索引。更改这行代码:
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]
我为所有页面运行了你的解析器,它工作正常。
推荐阅读
- identityserver4 - 当身份服务器发送未经授权的 401 消息时,如何添加 error_response
- c# - 如何从 LINQ-to-SQL 大型数据集更新中获得更好的性能
- ios - 如何分别删除有关 Firebase/Analytics 和 swizzing 的 firebase 警告和控制台消息?
- javascript - 如何循环遍历数组并打印出正值?
- ruby-on-rails - Rails 的嵌套形式给出了 Unpermitted 参数的问题::image
- c# - 递归类型数组的递归方法重复值
- c# - 在 ASP.NET Core 中测量异步与同步代码的性能
- javascript - 在没有连接 HOC 的情况下使用带有 react-hooks 的 redux
- php - 从单行获取具有多个值的mysql
- java - Spring security 在所有 api 端点上给出 401