我正在向一个网站发帖请求,该网站包含多家商店的店名、街道和城市,每个商店都有自己的卡片。我正在尝试使用xpath从站点记录这些数据。有一小部分项目(例如商店名称)无法读取,从而生成索引器,我正在尝试使用try except处理这些错误。
在下面的代码中,只有在读取单个title变量并将其附加到名称列表时出错。我的代码捕捉到了异常,但由于某种原因,当我知道异常发生在“place3”中时,这个“X_NAME_ERROR_X”元素会被追加到列表的末尾,例如。[“place1”、“place2”、“place4”、“X_NAME_ERROR_X']。
python为什么会在列表的末尾附加excepted code变量,甚至认为异常应该在for循环结束之前出现?
rest_count = len(response.html.xpath('//*[@id="search-results-container"]//div[@class="mb-32 width--full"]'))
names = []
street_address = []
city_address = []
for item in range(rest_count):
try:
title = response.html.xpath('//*[@id="search-results-container"]//div[@class="mb-32 width--full"]/h4/text()')[item]
names.append(title)
except IndexError:
title = 'X_NAME_ERROR_X'
names.append(title)
try:
street = response.html.xpath('//*[@id="search-results-container"]//div[@class="mb-32 width--full"]/p[1]/text()')[item]
street_address.append(street)
except IndexError:
street = 'X_STREET_ERROR_X'
street_address.append(street)
try:
city = response.html.xpath('//*[@id="search-results-container"]//div[@class="mb-32 width--full"]/p[2]/text()')[item]
city_address.append(city)
except IndexError:
city = 'X_CITY_ERROR_X'
city_address.append(city)