我正在用Scrapy ( https://www.tripadvisor.com/Hotel_Review-g189541-d15051151-Reviews-CitizenM_Copenhagen_Radhuspladsen-Copenhagen_Zealand.html )抓取Tripadvisor。
我收集的其中一个项目是景点数量和半径,以及餐厅的数量和半径。此信息并不总是存在( https://www.tripadvisor.com/Hotel_Review-g189541-d292667-Reviews-Strandmotellet_Greve-Copenhagen_Zealand.html )。如果它不存在,我会得到这个错误消息:"IndexError: list index out of range“( https://pastebin.com/pphM8FSM)
我试着写一个try-error结构,但没有成功:
try:
nearby_restaurants0_attractions1_distance = response.css("._1aFljvmJ::text").extract()
except IndexError:
nearby_restaurants0_attractions1_distance = [None,None]
items["hotel_nearby_restaurants_distance"] = nearby_restaurants0_attractions1_distance[1]
items["hotel_nearby_attractions_distance"] = nearby_restaurants0_attractions1_distance[2]非常感谢你的帮助!
发布于 2020-08-06 02:29:09
列表索引是从零开始的,而不是从1开始。如果您期望的是包含两个项目的列表,则需要修改最后两行以使用[0]和[1],而不是[1]和[2]
items["hotel_nearby_restaurants_distance"] = nearby_restaurants0_attractions1_distance[0]
items["hotel_nearby_attractions_distance"] = nearby_restaurants0_attractions1_distance[1]我也不确定IndexError是不是来自数据丢失的时候。即使在数据存在的情况下,它也可能只是遇到了这个错误。如果数据丢失,您可能需要捕获不同的异常。
发布于 2020-08-06 18:46:08
对于感兴趣的每个人,请回答:
Scrapy在nearby_restaurants0_attractions1_distance中搜索项目,但如果什么也找不到,则返回None。所以在那个阶段没有IndexError。
当items只获取列表的一部分时,IndexError就会发生--当Scrapy返回一个None对象时,列表显然不存在。粘贴箱还会在IndexError上方的一行中显示项目的问题
nearby_restaurants0_attractions1_distance = response.css("._1aFljvmJ::text").extract()
try:
items["hotel_nearby_restaurants_distance"] = nearby_restaurants0_attractions1_distance[1]
except IndexError:
items["hotel_nearby_restaurants_distance"] = None
try:
items["hotel_nearby_attractions_distance"] = nearby_restaurants0_attractions1_distance[2]
except:
items["hotel_nearby_attractions_distance"] = Nonehttps://stackoverflow.com/questions/63271389
复制相似问题